JS DOM: Node Type
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.
1means it's a HTML or XML node.3means its content.
Here is a complete list of possible return values.
| value | meaning |
|---|---|
| 1 | ELEMENT_NODE |
| 2 | ATTRIBUTE_NODE |
| 3 | TEXT_NODE |
| 4 | CDATA_SECTION_NODE |
| 5 | ENTITY_REFERENCE_NODE |
| 6 | ENTITY_NODE |
| 7 | PROCESSING_INSTRUCTION_NODE |
| 8 | COMMENT_NODE |
| 9 | DOCUMENT_NODE |
| 10 | DOCUMENT_TYPE_NODE |
| 11 | DOCUMENT_FRAGMENT_NODE |
| 12 | NOTATION_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.