Number of elements a particular tag contains in JavaScript?


Javascript has provided childElementCount property to return the number of elements a tag contains in it. The returned value contains only the number but not the values such as the names of the elements etc.

syntax

document.getElementById("myDIV").childElementCount;

It only takes the id name of the tag and returns the number of elements in the tag.

Example

In the following example, there are two elements in the div tag. Using the property "childElementCount" the number of elements was found out and the result is displayed in the output.

Live Demo

<html>
<body>
<div id="DIV">
   <p>First element</p>
   <p>Second element</p>
</div>
<p id = "cou"></p>
<script>
   var cou = document.getElementById("DIV").childElementCount;
   document.getElementById("cou").innerHTML = "number of elements :" +" "+ cou;
</script>
</body>
</html>

Output

First element
Second element

number of elements : 2
raja
Published on 08-Aug-2019 09:14:43
Advertisements