With W3C defined TreeWalker interface –now you can quickly access the required nodes. createTreeWalker() method can create an object of TreeWalker. Let’s see it by a JavaScript example: The above code creates a tree with its root as the specified rootnode. This means you can actually get hold of any sub-tree within DOM! And in case you’re interested in working with the entire DOM you can get the complete tree by using BODY element as root. BODY element covers all the visible element on a webpage. Caveat (as usual!): As far as I know, IE 8 (or lesser) does not support this method. Firefox/Chrome/Opera do support it. Hopefully IE 9 and above will have support for this method. You can check it out in your browser. Isn’t that a beauty?! In the first line, you get a handle on any element by its ID and then provide this element to the createTreeWalker() method to get the full DOM tree under that element. What’s more?! You can also specify which TYPE of nodes in the sub-tree you want to play with. NodeFilter Interface defines 15 different constants to help you in this. Of these constants, you’ll mostly use the following: NodeFilter.SHOW_ALL (for selecting all the nodes) NodeFilter.SHOW_ELEMENT (for selecting only the text nodes) NodeFilter.SHOW_ATTRIBUTE (for selecting only the attribute nodes) NodeFilter.SHOW_TEXT (for selecting only the element nodes) Here is an example function that will give you access to all the TEXT nodes: Using a simple while loop, you can walk through all the nodes present in a DOM sub-tree. In the above example, sub-tree with only text nodes is returned. Traversing DOM is often performed while developing web applications with JavaScript, Perl, Python etc. For example, the other day when I needed to randomize an HTML list, I had to grab all the LI nodes and then shuffle them. Although, in that case used another method for accessing nodes. I hope this method will help you in writing better and easier code. Comment * Name * Email * Website
Δ