Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element has no method hasAttribute, Why?

Tags:

javascript

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 .

like image 566
jenswirf Avatar asked Sep 18 '25 18:09

jenswirf


2 Answers

The 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'))
) {
like image 136
Quentin Avatar answered Sep 20 '25 06:09

Quentin


var el = evt.target is a document object and therefore does not have a hasAttribute attribute.

like image 34
Farhan Ahmad Avatar answered Sep 20 '25 06:09

Farhan Ahmad