HTML DOM children Property

HTMLWeb DevelopmentFront End Technology

The HTML DOM children property is used to return all the child elements of the specified element in the form of HTML collection. It is only a read-only property. The elements obtained can then be accessed by using index numbers which starts from 0.

The elements appear in the same order as they are in the HTML document. It contains only children nodes and doesn’t include whitespace and comments like childNodes property.

Syntax

Following is the syntax for the children property −

element.children

Let us see an example of the HTML DOM children property −

<!DOCTYPE html>
<html>
<head>
<style>
   div {
      border: 1px solid blue;
      margin: 7px;
   }
</style>
</head>
<body>
<p>Click the button below to find out the number of div element children</p>
<button onclick="myChild()">COUNT</button>
<div id="DIV1">
<p>First p element </p>
<p>Second p element </p>
</div>
<p id="Sample"></p>
<script>
   function myChild() {
      var x = document.getElementById("DIV1").children.length;
      document.getElementById("Sample").innerHTML = "The div element has "+x+" child nodes";
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking COUNT button −

In the above example −

We have created a

element with id “DIV1” and it has two paragraphs inside it. We have added a color border and some margin to distinguish it from other elements −


div {
   border: 1px solid blue;
   margin: 7px;
}
<div id="DIV1">
<p>First p element </p>
<p>Second p element</p>
</div>

We have then created a COUNT button which will execute myChild() function when clicked by the user −

<button onclick="myChild()">COUNT</button>

The myChild() function gets the element which has id equals “DIV1” which in our case is the <div> element and gets its children.length property value and assigns it to the variable x. Important thing here is the children property does not consider whitespace and comments so it will only consider the two <p> elements and the children.length will return 2. This value is then displayed in the paragraph with id “Sample” using the innerHTML() method −

function myChild() {
   var x = document.getElementById("DIV1").children.length;
   document.getElementById("Sample").innerHTML = "The div element has "+x+" child nodes";
}
raja
Published on 07-Aug-2019 16:17:52
Advertisements