HTML DOM nodeType Property


The HTML DOM nodeType property returns a number corresponding to the type of the node.

Following is the syntax −

Returning number value

Node.nodeType

Here, the return value can be the following −

  • Number ‘1’ for element nodes
  • Number ‘2’ for attribute nodes
  • Number ‘3’ for text nodes
  • Number ‘8’ for comment nodes

NOTE: Whitespaces are considered as text nodes only.

Let us see an example of HTML DOM nodeType property −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM nodeType</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
</style>
</head>
<body>
   <form>
      <fieldset>
         <legend>HTML-DOM-nodeType</legend>
         <label for="example">Example site: </label>
         <input id="urlSelect" type="url" name="urlAddress" value="http://www.example.com" disabled>
         <input type="button" onclick="getNodeTypes()" value="Get all Types">
         <div id="divDisplay"></div>
      </fieldset>
   </form>
<script>
   var urlSelect = document.getElementById("urlSelect");
   var commentNode = document.createComment("My Example URL");
   urlSelect.appendChild(commentNode);
   var divDisplay = document.getElementById("divDisplay");
   function getNodeTypes() {
      divDisplay.textContent = 'Body: '+document.body.nodeType;
      divDisplay.textContent += ' & input: '+urlSelect.nodeType;
      divDisplay.textContent += ' & comment: '+commentNode.nodeType;
}
</script>
</body>
</html>

Output

Before clicking ‘Get all Types’ button −

After clicking ‘Get all Types’ button −

Updated on: 25-Oct-2019

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements