Monday, February 18, 2008

XML Nodetype Constants

Update, 04.03.08: It appears I was fooled by Prototype. The Node-interface/object is not available in IE.
..if (!window.Node) var Node = { };

if (!Node.ELEMENT_NODE) {
// DOM level 2 ECMAScript Language Binding
Object.extend(Node, {
ELEMENT_NO..


From reading JS-code in different places, it doesn't look like many people are aware that there are constants for the different node-types in a HTML/XML-document.

Most code I've come over tests the type like this:
if( xmlNode.nodeType == 1 )

Which is ok, if you remember that 1 corresponds with element-nodes. The Node-interface in DOM level 1 contains a property/constant for each of the nodetypes.

A list of the constants:
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

A more readable version to the previous test:
if( xmlNode.nodeType === Node.ELEMENT_NODE )

0 comments: