236
Chapter 4
if (someNode.nodeType == Node.ELEMENT_NODE) {
// Do something with the element node
} else if (someNode.nodeType == Node.TEXT_NODE) {
// Do something with the text node
}
I like most of this DOM stuff so far, but all
this null value and undened stuff kind of
freaks me out. Can’t I just ask the node if it’s
an element, or text, or whatever?
Every node has a property called nodeType,
along with the nodeName and nodeValue
proeprties that you’ve already seen. The
nodeType property returns a number, and that
number maps to a value stored in the Node class.
There’s a value for each type of node, so you can
use these values to gure out exactly what kind
of node you’re working with, like this:
You can! (well, sort of)
Here’s the nodeType property.
It returns a number...
...that you can compare to the
numbers dened in the Node class.
There are numbers dened
for all the node types,
including elements, text,
and attributes.
Once you know what type
of node you have, you can
avoid using properties that
would return null values.
node types