EN
JavaScript - check node type
0
points
In this article, we would like to show you how to check node type using JavaScript.
Quick solution:
node.nodeType
Values
| Value | Type | Description |
|---|---|---|
1 | Node.ELEMENT_NODE | elements like <p> or <div> |
2 | Node.ATTRIBUTE_NODE | an attribute of an element |
3 | Node.TEXT_NODE | the text inside an element or attribute |
4 | Node.CDATA_SECTION_NODE | a CDATASection, such as <!CDATA[[ … ]]> |
7 | Node.PROCESSING_INSTRUCTION_NODE | a ProcessingInstruction of an XML document, such as <?xml-stylesheet … ?> |
8 | Node.COMMENT_NODE | a Comment node, such as <!-- comment text --> |
9 | Node.DOCUMENT_NODE | a Document node. |
10 | Node.DOCUMENT_TYPE_NODE | a DocumentType node, such as <!DOCTYPE html> |
11 | Node.DOCUMENT_FRAGMENT_NODE | a DocumentFragment node |
Note:
Deprecated types that are not in use anymore:
Node.ENTITY_REFERENCE_NODE(5),Node.ENTITY_NODE(6),Node.NOTATION_NODE(12).
Practical example
In this example, we get handles to different nodes and display their types in the console.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="my-div">Example text...</div>
<script>
var myDiv = document.querySelector('#my-div');
console.log(myDiv.nodeType); // 1 - ELEMENT_NODE
var myDivAttribute = myDiv.attributes[0];
console.log(myDivAttribute.nodeType); // 2 - ATTRIBUTE_NODE
var myDivText = myDiv.firstChild;
console.log(myDivText.nodeType); // 3 - TEXT_NODE
console.log(document.nodeType); // 9 - DOCUMENT_NODE
</script>
</body>
</html>