04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11: DOM Levels 2 and 3<br />

Perhaps this is too much information, and you really only want to return the < li > elements that occur in<br />

the traversal. This can be accomplished by using a filter, as shown in the following example:<br />

var div = document.getElementById(“div1”);<br />

var filter = function(node){<br />

return node.tagName.toLowerCase() == “li” ?<br />

NodeFilter.FILTER_ACCEPT :<br />

NodeFilter.FILTER_SKIP;<br />

};<br />

var iterator = document.createNodeIterator(div, NodeFilter.SHOW_ELEMENT,<br />

filter, false);<br />

var node = iterator.nextNode();<br />

while (node !== null) {<br />

alert(node.tagName);<br />

node = iterator.nextNode();<br />

}<br />

//output the tag name<br />

In this example, only < li > elements will be returned from the iterator.<br />

The nextNode() and previousNode() methods work with NodeIterator ’ s internal pointer in the<br />

DOM structure, so changes to the structure are represented appropriately in the traversal.<br />

Firefox versions prior to 3.1 do not implement the createNodeIterator() method,<br />

though they do support createTreeWalker() as discussed in the next section.<br />

TreeWalker<br />

TreeWalker is a more advanced version of NodeIterator . It has the same functionality, including<br />

nextNode() and previousNode() , and adds the following methods to traverse a DOM structure in<br />

different directions:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

parentNode() — Travels to the current node ’ s parent<br />

firstChild() — Travels to the first child of the current node<br />

lastChild() — Travels to the last child of the current node<br />

nextSibling() — Travels to the next sibling of the current node<br />

previousSibling() — Travels to the previous sibling of the current node<br />

A TreeWalker object is created using the document.createTreeWalker() method, which accepts the<br />

same three arguments as document.createNodeIterator() : the root to traverse from, which node types<br />

347

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!