JS DOM: Node Type

By Xah Lee. Date: . Last updated: .

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.

Get Node Type

node.nodeType

Return node type.

  • The return value is a number.
  • Usually 1 or 3.
  • 1 means it's a HTML or XML node.
  • 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
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.

JS DOM, About Node, Node Type