Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DOM parentNode and parentElement

Can somebody explain in simple terms, what is the difference between classical DOM parentNode and newly introduced in Firefox 9 parentElement

like image 523
shabunc Avatar asked Dec 31 '11 01:12

shabunc


People also ask

Should I use parentElement or parentNode?

Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.

What is parentElement?

Definition and Usage The parentElement property returns the parent element of the specified element. The difference between parentElement and parentNode, is that parentElement returns null if the parent node is not an element node: body. parentNode; // Returns the <html> element.

What does parentNode mean?

A Node that is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.

What is parentNode parentNode in Javascript?

Definition and Usage. The parentNode property returns the parent node of an element or node. The parentNode property is read-only.


1 Answers

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element document.body.parentElement; // the <html> element  document.documentElement.parentNode; // the document node document.documentElement.parentElement; // null  (document.documentElement.parentNode === document);  // true (document.documentElement.parentElement === document);  // false 

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

like image 138
lonesomeday Avatar answered Sep 24 '22 21:09

lonesomeday