Languages
[Edit]
EN

JavaScript - check node type

0 points
Created by:
James-Z
767

In this article, we would like to show you how to check node type using JavaScript.

Quick solution:

node.nodeType

 

Values

ValueTypeDescription
1Node.ELEMENT_NODEelements like <p> or <div>
2Node.ATTRIBUTE_NODEan attribute of an element
3Node.TEXT_NODEthe text inside an element or attribute
4Node.CDATA_SECTION_NODECDATASection, such as <!CDATA[[ … ]]>
7Node.PROCESSING_INSTRUCTION_NODEProcessingInstruction of an XML document, such as <?xml-stylesheet … ?>
8Node.COMMENT_NODEComment node, such as <!-- comment text -->
9Node.DOCUMENT_NODEa Document node.
10Node.DOCUMENT_TYPE_NODEa DocumentType node, such as <!DOCTYPE html>
11Node.DOCUMENT_FRAGMENT_NODEDocumentFragment 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>

References

  1. Node.nodeType - Web APIs | MDN

Alternative titles

  1. JavaScript - check nodeType (DOM)
  2. JavaScript - get nodeType integer number (DOM)
  3. JavaScript - check HTML element / node type
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join