Navigating the DOM tree |
var sports = document.getElementById('sports');
<< undefined
sports.childNodes;
<< NodeList [ #text "
", <p.swim>, #text "
", <p#bike>, #text "
", <p>, #text "
" ]
<< undefined
sports.childNodes;
<< NodeList [ #text "
", <p.swim>, #text "
", <p#bike>, #text "
", <p>, #text "
" ]
Note that the childNodes property returns all the nodes that are children of an element. This will include any text nodes and since whitespace is treated as a text node, there will often be empty text nodes in this collection.
The children property only returns any element nodes that are children of that node, so will ignore any text nodes. Note that this is only supported in Internet Explorer from version 9 onwards:
sports.children // this will only contain paragraph elements
<< HTMLCollection [ <p>, <p>, <p> ]
sports.children.length
<< 3
<< HTMLCollection [ <p>, <p>, <p> ]
sports.children.length
<< 3
The firstChild property returns the first child of a node:
sports.firstChild
<< #text "
"
<< #text "
"
And the lastChild property returns the last child of a node:
sports.lastChild
<< #text "
"
<< #text "
"
Be careful when using these properties―the first or last child node can often be a text node, even if it’s just an empty string generated by some whitespace.
For example, you might expect the first child node of the sports element to be the swim element and the last child to be the run element, but it is in fact a text node, generated by the whitespace characters in between the <section> and <p> tags:
The parentNode property returns the parent node of an element. The following code returns the sports node because it is the parent of the bike node:
bike.parentNode;
<< <section id="sports">
<< <section id="sports">
The nextSibling property returns the next adjacent node (that is, the same parent). It will return null if the node is the last child node of that parent:
bike.nextSibling;
<< #text "
"
<< #text "
"
The previousSibling property returns the previous adjacent node. It will return null if the node is the first child of that parent:
bike.previousSibling
<< #text "
"
<< #text "
"
Once again, these methods find the next and previous node, not element, so they will often return a blank text node as in the examples above.
Using these properties allows you to navigate around the whole of the document tree.
0 Response to "Navigating the DOM Tree"
Post a Comment