Main Page

Checking the node type

Checking the node type
You can check the type of node by using the
nodeType
property:
alert(document.nodeType); //outputs “9”
alert(document.documentElement.nodeType); //outputs “1”
In this example,
document.nodeType
returns
9
, which is equal to
Node.DOCUMENT_NODE
, and
docu-
ment.documentElement.nodeType
returns
1
, which is equal to
Node.ELEMENT_NODE
.
You can also match up these values with the
Node
constants:
alert(document.nodeType == Node.DOCUMENT_NODE); //outputs “true”
alert(document.documentElement.nodeType == Node.ELEMENT_NODE); //outputs “true”
This code works in Mozilla 1.0+, Opera 7.0+, and Safari 1.0+. Unfortunately, Internet Explorer doesn’t
support these constant values, so this code causes an error. You can remedy the situation by defining
your own constants that match the node type constants, such as the following:
if (typeof Node == “undefined”) {
var Node = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
}
}
The other option is to use the integer literals (although this may get confusing because not many people
have memorized the node type values).
Dealing with attributes
As mentioned previously, only
Element
nodes have attributes even though the
Node
interface has an
attributes
method that is inherited by all node types. The attributes property for an
Element
node is
a
NamedNodeMap
, which provides several methods for accessing and manipulating its contents:
?
getNamedItem(
name
)
— returns the node whose
nodeName
property is equal to
name
?
removeNamedItem(
name
)
— removes the node whose
nodeName
property is equal to
name
from the list
?
setNamedItem(
node
)
— adds the
node
into the list, indexing it by its
nodeName
property
?
item(
pos
)
— just like
NodeList
, returns the node in the numerical position
pos
169
DOM Basics
09_579088 ch06.qxd 3/28/05 11:37 AM Page 169


JavaScript EditorFree JavaScript Editor     Ajax Editor


©