How to Get the Node Type of a DOM Element in JavaScript



In this article, you will learn how to get the node type of a DOM element in JavaScript.

Getting the node type of a DOM element in JavaScript

In JavaScript, you can get the node type of a DOM element using the nodeType property. This property returns an integer that represents the type of the node. Here are the possible node types and their corresponding integer values:

  • 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

To get the node type of a DOM element, you can simply access its nodeType property.

const element = document.getElementById('myElement');
const nodeType = element.nodeType;
console.log(nodeType); // Output: an integer representing the node type

Note that the nodeType property returns the same integer value for all elements of the same node type, regardless of their tag name or attributes. For example, both

and elements have a node type of 1 because they are both element nodes.

In addition to the nodeType property, you can also use the nodeName property to get the tag name of an element node.

const element = document.getElementById('myElement');
if (element.nodeType === 1) {
  const tagName = element.nodeName;
  console.log(tagName); // Output: the tag name of the element

This example first checks if the node type of the element is 1 (element node), and then gets its tag name using the nodeName property.