JS DOM: Node Type
What is node type
Node type is a integer that indicates the type of the node.
Get node type
node.nodeType-
Return node type.
The return value is a integer.
each possible return integer has a equivalent constant property for easy reading. For example, value of
Node.ELEMENT_NODEis 1.most common values are 1 and 3.
1means it's a HTML or XML element (an element is represented by a tag markup).3means text node (the content of a tag or text between tags.).Here is a complete list of possible return values.
- 1 =
Node.ELEMENT_NODE. Element node means it is represented by a tag, in html or xml source code. e.g. html tags. see HTML: List of HTML Tags - 2 =
Node.ATTRIBUTE_NODE - 3 =
Node.TEXT_NODE - 4 =
Node.CDATA_SECTION_NODE - 5 =
Node.ENTITY_REFERENCE_NODE - 6 =
Node.ENTITY_NODE - 7 =
Node.PROCESSING_INSTRUCTION_NODE - 8 =
Node.COMMENT_NODE. see HTML: Comment - 9 =
Node.DOCUMENT_NODE - 10 =
Node.DOCUMENT_TYPE_NODE. see HTML: Doctype - 11 =
Node.DOCUMENT_FRAGMENT_NODE - 12 =
Node.NOTATION_NODE
some of these types are obsolete.
console.log(1 === Node.ELEMENT_NODE); console.log(2 === Node.ATTRIBUTE_NODE); console.log(3 === Node.TEXT_NODE); console.log(4 === Node.CDATA_SECTION_NODE); console.log(5 === Node.ENTITY_REFERENCE_NODE); console.log(6 === Node.ENTITY_NODE); console.log(7 === Node.PROCESSING_INSTRUCTION_NODE); console.log(8 === Node.COMMENT_NODE); console.log(9 === Node.DOCUMENT_NODE); console.log(10 === Node.DOCUMENT_TYPE_NODE); console.log(11 === Node.DOCUMENT_FRAGMENT_NODE); console.log(12 === Node.NOTATION_NODE); // all true - 1 =
Example. show different node types
// example of node type 1 = Node.ELEMENT_NODE. // this is the html tag, the root element console.log(document.documentElement.nodeType === 1); console.log(document.documentElement.nodeName === "HTML"); console.log(document.documentElement.nodeValue === null);
// example of node type 3 = Node.TEXT_NODE document.body.append("good morn"); const xx = document.body.lastChild; console.log(xx.nodeType === 3); console.log(xx.nodeName === "#text"); console.log(xx.nodeValue === "good morn");
/* Example of node type 9 = Node.DOCUMENT_NODE. The value of “document” is the entire page. */ console.log(document.nodeType === 9); console.log(document.nodeName === "#document"); console.log(document.nodeValue === null);
// Example of node type 10 = Node.DOCUMENT_TYPE_NODE. console.log(document.doctype.nodeType === 10); console.log(document.doctype.nodeName === "html"); console.log(document.doctype.nodeValue === null);
Browser support
As of 2012-04-29, this works in all major browsers.