How to count all child elements of a particular element using JavaScript ?


To count all child elements of a particular element using JavaScript, we can use the childElementCount property or the children property.

Method 1: Using childElementCount property

The childElementCount property returns the number of child elements of a particular element. Here's an example:

<div id="parent">
  <p>Child 1</p>
  <p>Child 2</p>
  <p>Child 3</p>
</div>
const parent = document.getElementById('parent');
const childCount = parent.childElementCount;
console.log(childCount); // Output: 3

Method 2: Using children property

The children property returns a collection of child elements of a particular element. We can then use the length property of the collection to get the count of child elements. Here's an example:

<div id="parent">
  <p>Child 1</p>
  <p>Child 2</p>
  <p>Child 3</p>
</div>
const parent = document.getElementById('parent');
const childCount = parent.children.length;
console.log(childCount); // Output: 3

Both methods will give the same output.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.