Thursday, October 29, 2009

TreeWalker: The ultimate DOM traversal provider

The W3C's DOM Level 2 calls for the existence of a JavaScript class by the name of TreeWalker, which all DOM Level 2-compliant browsers (amongst the modern ones, this is all but the IE browsers) have successfully provided. But wouldn't it be nice to have a TreeWalker available in IE too? This is the question that was raised at work during a story with very intense JavaScript requirements. And so, I set out to build a cross-browser TreeWalker (obviously leveraging the native TreeWalker when available). I blew through a number of methods easily (parentNode(), firstChild(), lastChild(), previousSibling(), nextSibling()), but had to call it quits for the night when I got to previousNode() and nextNode()... much too complicated to think about at the late hour. I did get some confirmation by looking at Mozile's (Mozilla In-Line Editor) TreeWalker JS (http://mozile.mozdev.org/0.8/src/dom/TreeWalker.js).

Looks like they also have some JS files in the same folder (http://mozile.mozdev.org/0.8/src/dom/InternetExplorerRange.js and http://mozile.mozdev.org/0.8/src/dom/InternetExplorerSelection.js) to give IE ranges/selections the capabilities of a W3C Range and the Mozilla Selection object, respectively, that I may have to peek at to see if I can refactor any of the RangeInformation class I put together to wrap ranges in a mostly cross-browser fashion.

Along with the Selection library I've recently created, I'd love to publish a copy of the TreeWalker to the open source world. We'll see....


Update:
Upon second inspection the next day, it turned out that parentNode, firstChild, lastChild, nextSibling, previousSibling were all actually harder methods than I had given them credit for, and nextNode and previousNode were actually the easy ones. The complications come from the whole "logical view" as defined in the W3C spec for DOM Traversal (DOM level 2) that features the TreeWalker.

No comments:

Post a Comment