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
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Edit: Some of this is wrong. See comments below for details
All
Element
objects are alsoNode
objects (becauseElement
is a descendent ofNode
). But there is aNode
which isn't anElement
... thedocument
object. So your<html>
element has a parent node (document
) but it doesn't have a parent element.The reason that there's a need for
parentElement
instead ofparentNode
is because, HTML5 doesn't strictly require an<html>
element, so almost any element can have a parent node without actually having a parent element. So if my HTML page looked like this:Then the
title
,header
,#body
andfooter
elements would have theirparentNode
asdocument
, but theirparentElement
would be null. Only thep
tag would have aparentElement
, which is#body
. (Note that I wouldn't advise this as a page structure... stick to something more traditional.)You can replicate it with something like this:
Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns
Element
ornull
. Properties without can return any other kind of node.Use
.parentElement
and you can't go wrong as long as you aren't using document fragments.If you use document fragments, then you need
.parentNode
:Also:
Apparently the
<html>
's.parentNode
links to the Document. This should be considered a decision phail as documents ain't Nodes since Nodes are defined to be containable by documents and documents can't be contained by documents.In Internet Explorer,
parentElement
is undefined for SVG elements, whereasparentNode
is defined.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'sparentNode
is not an element. If so,parentElement
isnull
.As an example:
Since the
<html>
element (document.documentElement
) doesn't have a parent that is an element,parentElement
isnull
. (There are other, more unlikely, cases whereparentElement
could benull
, but you'll probably never come across them.)