HTML DOM hasChildNodes() method


The HTML DOM hasChildNodes() method is used for checking if an element contains child nodes or not. It returns true if the element does contain child nodes otherwise it returns false. It will consider any whitespace as child nodes as whitespace inside the node are basically considered as text nodes.

Syntax

Following is the syntax for hasChildNodes() method −

node.hasChildNodes()

Example

Let us look at an example for the hasChildNodes() method −

Live Demo

<!DOCTYPE html>
<html>
<head>
<script>
   function checkChild() {
      var div = document.getElementById("DIV1").hasChildNodes();
      document.getElementById("Sample").innerHTML = div;
   }
</script>
</head>
<body>
<h1> hasChildNodes() method example</h1>
<div id="DIV1">
<p>This is a p element inside the div element</p>
<span>This is a span element inside the div element</span>
</div>
<br>
<button onclick="checkChild()">CHECK</button>
<p id="Sample"></p>
</body>
</html>

Output

This will produce the following output −

On clicking the CHECK button −

In the above example −

We have first created a <div> element with id “DIV1” and it contains a <p> element and a <span> element inside it −

<div id="DIV1">
<p>This is a p element inside the div element</p>
<span>This is a span element inside the div element</span>
</div>

We have then created a button CHECK that will execute the checkChild() method when clicked by the user −

<button onclick="checkChild()">CHECK</button>

The checkChild() method uses the getElementById() method to get the corresponding <div> element and the hasChildNodes() method on it. Since the div element has two child inside it, therefore it will return true. The same is displayed in the paragraph with id “Sample” using its innerHTML property −

function checkChild() {
   var div = document.getElementById("DIV1").hasChildNodes();
   document.getElementById("Sample").innerHTML = div;
}

Updated on: 19-Feb-2021

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements