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 />

258<br />

document.nodeType;<br />

// 9<br />

Did you get 9? Yup, me too. nodeType will always be 9 for a Document node. And for Element and Text<br />

nodes, nodeType will always be 1 and 3, respectively. Write those down for later reference, as in Table 7–1.<br />

Table 7–1. nodeType Literals for Commonly Scripted Nodes<br />

Node nodeType Literal<br />

Element 1<br />

Text 3<br />

Document 9<br />

nodeType commonly appears in the boolean expression for if conditions. Say you want to be sure<br />

you have an Element node on your hands, you might write an if condition comparing nodeType to 3. If<br />

=== returns true, you may query any of the members or invoke any of the methods listed in the Element<br />

interface in the if block. So, you do something like this:<br />

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

// do something to Element node<br />

}<br />

In addition to testing nodeType with number literals, you can do so with constants, that is to say, in<br />

Firefox, Safari, and Opera. As of version 8, Internet Explorer still does not implement nodeType constants.<br />

However, you can create those for Internet Explorer. Just code an if condition testing whether window<br />

has a Node member. If not, create one like so:<br />

if (typeof Node === "undefined") {<br />

var Node = {ELEMENT_NODE: 1, TEXT_NODE: 3, DOCUMENT_NODE: 9}<br />

}<br />

Note that you are just adding the nodeType constants commonly scripted. There are nine more of<br />

those. But you won’t need them for anything.<br />

Having created the Node object in the event that it is missing, you can now rewrite the nodeType test<br />

like so:<br />

if (nodeFromTree.nodeType === Node.ELEMENT_NODE) {<br />

// do something to Element node<br />

}<br />

Constants do read better than number literals. But most JavaScript programmers just go with the<br />

number literals, viewing laziness as a virtue. Even so, let’s add a nodeType constant column, as in Table<br />

7–2.

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

Saved successfully!

Ooh no, something went wrong!