Accessing Nodes by Type, Name or Value

Contact Us or call 1-877-932-8228
Accessing Nodes by Type, Name or Value

Accessing Nodes by Type, Name or Value

The element.nodeType Property

Every node has a nodeType property, which contains an integer corresponding to a specific type. For example, 1 is an element node, 2 is an attribute node, 3 is a text node, etc. The W3C DOM specifies a set of constants that correspond to these integers. These constants are properties of every node. Unfortunately, Internet Explorer's DOM doesn't support these constants, so we're stuck with using the integers. For reference, the constants are listed below:

Node Type Constants
Constant Integer
node.ELEMENT_NODE 1
node.ATTRIBUTE_NODE 2
node.TEXT_NODE 3
node.CDATA_SECTION_NODE 4
node.ENTITY_REFERENCE_NODE 5
node.ENTITY_NODE 6
node.PROCESSING_INSTRUCTION_NODE 7
node.COMMENT_NODE 8
node.DOCUMENT_NODE 9
node.DOCUMENT_TYPE_NODE 10
node.DOCUMENT_FRAGMENT_NODE 11
node.NOTATION_NODE 12

To find all of a node's child element nodes, you would loop through its childNodes collection checking each node one by one:

for (var i=0; i<node.childNodes.length; i++) {
	if (node.childNodes[i].nodeType==1) {
		alert("This is an element node.");
	}
}

The element.nodeName Property

Every node also has a nodeName property. For elements and attributes, the nodeName property returns the tag name and attribute name, respectively. For other node types, the nodeName property returns a string beginning with a pound sign (#) and indicating the node type (e.g, #text or #comment).

The element.nodeValue Property

The nodeValue property is usually used with text nodes and it simply returns the text value of the node. Though, it can also be used to return the value of attributes, comments, processing instructions and CDATA sections. For all other node types, it returns null.

Next