JS: Node Type

By Xah Lee. Date: .

What is Node Type?

Node type is a integer that indicates the type of the node.

There are unusual kind of nodes. For example:

normally, you just want to know the Node Name (aka tag name) or Node value (the content of a node.) But because some nodes are Whitespace Nodes or comment or special, you need to check if node type is the right type, then you can query node name or value. (else you'll get error or null.)

get Node Type

node.nodeType
Return node's type.

The return value is a number. Usually 1 or 3. “1” means it's a HTML/XML element. “3” means its content.

Here is a complete list of possible return values.

html element node type
valuemeaning
1ELEMENT_NODE
2ATTRIBUTE_NODE
3TEXT_NODE
4CDATA_SECTION_NODE
5ENTITY_REFERENCE_NODE
6ENTITY_NODE
7PROCESSING_INSTRUCTION_NODE
8COMMENT_NODE
9DOCUMENT_NODE
10DOCUMENT_TYPE_NODE
11DOCUMENT_FRAGMENT_NODE
12NOTATION_NODE
// show the root node “document”'s type, name, value
document.nodeType   // 9
document.nodeName   // "#document"
document.nodeValue  // null
// root element has 2 child
document.childNodes.length // 2

// this is <!doctype html>
document.childNodes[0].nodeType // 10
document.childNodes[0].nodeName // "html"
document.childNodes[0].nodeValue // null

// this is <html>
document.childNodes[1].nodeType // 1
document.childNodes[1].nodeName // "HTML"
document.childNodes[1].nodeValue // null
// example of a element node

// first paragraph element
let xx = document.getElementsByTagName("p")[0];

xx.nodeType // 1
xx.nodeName // "P"
xx.nodeValue // null
// example of a text node

// first paragraph's content
let xx = document.getElementsByTagName("p")[0].firstChild;

xx.nodeType // 3
xx.nodeName // "#text"
xx.nodeValue // a string of p's content

As of 2012-04-29, this works in all major browsers.

JavaScript/DOM: Node Name, Node Type, Node Value

BUY ΣJS JavaScript in Depth