How to count all child elements of a particular element using JavaScript ?
Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementCount property to count all the child elements of a particular element.
Syntax
node.childElementCount
Example:
<!DOCTYPE html> < html > < head > < title > How to count all child elements of a particular element using JavaScript? </ title > </ head > < body > < h1 style = "color:green" >GeeksforGeeks</ h1 > < h3 > Click the button to count all< br > children the div element </ h3 > < h5 >Count all child elements of < ul > elements</ h5 > < ul id = "parentID" > < li >First element</ li > < li >Second element</ li > < li >Third element</ li > < li >Fourth element</ li > </ ul > < button onclick = "myGeeks()" > Click Here! </ button > < h5 id = "GFG" ></ h5 > < script > // This function count the child elements function myGeeks() { var count = document.getElementById( "parentID").childElementCount; document.getElementById("GFG").innerHTML = "Total Number of Child node: " + count; } </ script > </ body > </ html > |
Output:
- Before Clicking the Button:
- After Clicking the Button:
Please Login to comment...