23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 7 ■ TRAVERSING AND MODIFYING THE DOM TREE<br />

276<br />

Figure 7–10. Using traverseTree() to convert the text of our list items to lowercase<br />

One final note on traverseTree(): although you stepped through child nodes by way of firstChild<br />

and nextSibling, you could have done so with lastChild and previousSibling, too. Click the Refresh<br />

icon in Firefox to revert the text in the elements to that from our markup, and then simply edit<br />

traverseTree(), changing firstChild to lastChild and nextSibling to previousSibling. Click Run to<br />

verify that traverseTree() works just as well traversing child nodes in reverse. More often than not, you<br />

will traverse child nodes moving forward with nextSibling rather than in reverse with previousSibling.<br />

function traverseTree(node, func) {<br />

func(node);<br />

node = node.lastChild;<br />

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

arguments.callee(node, func);<br />

node = node.previousSibling;<br />

}<br />

}<br />

var root = document.<br />

childNodes[1].<br />

childNodes[1].<br />

childNodes[1].<br />

childNodes[3];<br />

traverseTree(root, function(node) {<br />

if (node.nodeType === 3) {<br />

node.data = node.data.toLowerCase();<br />

}<br />

});

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

Saved successfully!

Ooh no, something went wrong!