HTML DOM childElementCount property is a read-only property that returns the number of child elements of a given element. The return type of childElementCount is unsigned long. It will only return the child elements of the queried node, not all child nodes of the HTML document.
The following is the syntax of childElementCount attribute-
node.childElementCount
Let us see an example of HTML DOM childElementCount attribute-
<!DOCTYPE html> <html> <head> <style> div { border: 2px solid blue; margin: 7px; padding-left:20px; } </style> </head> <body> <p>Click the button below to find out the no of children of the div element</p> <button onclick="childCount()">COUNT</button> <div id="myDIV"> <h3>HEADING</h3> <p>First p element</p> <p>Second p element</p> </div> <p id="Sample"></p> <script> function childCount() { var x = document.getElementById("myDIV").childElementCount; document.getElementById("Sample").innerHTML = "The div element has "+x+" children"; } </script> </body> </html>
This will produce the following output-
When the Count button is clicked-
In the above example -
We created an element with the id "myDIV" and three elements within it. Two
elements and a
div { border: 2px solid blue; margin: 7px; padding-left:20px; } <div id="myDIV"> <h3>HEADING</h3> <p>First p element</p> <p>Second p element</p> </div>
Then we created a button COUNT which will execute the childCount() method when clicked .
<button onclick="childCount()">COUNT</button>
childCount() method gets the element with id "myDIV" ( in our case ) element and assigns its childElementCount attribute value to variable x. Since there are two
elements and one
The returned value is then displayed in the paragraph with the id "Sample" using the innerHTML () method in the paragraph -
function childCount() { var x = document.getElementById("myDIV").childElementCount; document.getElementById("Sample").innerHTML = "The div element has "+x+" children"; }
The above is the detailed content of HTML DOM childElementCount property The childElementCount property returns the number of child elements of the specified element (excluding text nodes and comment nodes). grammar: element.childElementCount Example: var div = document.getElementById('myDiv'); var count = div.childElementCou. For more information, please follow other related articles on the PHP Chinese website!