Difference between DOM parentNode and parentElement

shabunc picture shabunc · Dec 31, 2011 · Viewed 150.3k times · Source

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

Answer

lonesomeday picture lonesomeday · Dec 31, 2011

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.)