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 .
console.log(el)
AFTER you do return el;
? The console.log(el)
will never be executed.
– jfriend00
Commented
May 30, 2012 at 15:28
The document
object:
parentNode
of the root element (if you were using HTML that would be the <html>
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;
}
}