admin管理员组文章数量:1316818
I'm trying to iterate "up" through the DOM nodes from a given element to get the first parent element which has the attribute 'animated'.
var el = evt.target;
console.log(el);
while (!el.hasAttribute('animated'))
{ el = el.parentNode; }
return el;
console.log(el);
Throws error:
>>>Uncaught TypeError: Object #<HTMLDocument> has no method 'hasAttribute'
How is this possible? I've clearly declared the variable el
and the first log is correct .
I'm trying to iterate "up" through the DOM nodes from a given element to get the first parent element which has the attribute 'animated'.
var el = evt.target;
console.log(el);
while (!el.hasAttribute('animated'))
{ el = el.parentNode; }
return el;
console.log(el);
Throws error:
>>>Uncaught TypeError: Object #<HTMLDocument> has no method 'hasAttribute'
How is this possible? I've clearly declared the variable el
and the first log is correct .
-
Why are you doing
console.log(el)
AFTER you doreturn el;
? Theconsole.log(el)
will never be executed. – jfriend00 Commented May 30, 2012 at 15:28
3 Answers
Reset to default 8The document
object:
- Is a node
- Is the
parentNode
of the root element (if you were using HTML that would be the<html>
element) - Is not an element.
Only elements have attributes, so only element objects have a hasAttribute
method.
You need to stop testing when you reach the document object (or when you aren't testing an element any longer).
while (
el.nodeType === 1 &&
(!el.hasAttribute('animated'))
) {
var el = evt.target
is a document
object and therefore does not have a hasAttribute
attribute.
You could also make it into a function that returns either null
or the ancestor node that has that attribute:
function findNodeWithAttribute(el, attr) {
while (true) {
if (!el || !el.hasAttribute) {
return null;
} else if (el.hasAttribute(attr)) {
return el;
}
el = el.parentNode;
}
}
本文标签: javascriptElement has no method hasAttributewhyStack Overflow
版权声明:本文标题:javascript - Element has no method hasAttribute, Why? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740298865a2257165.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论