To get the count of child elements inside a parent element, You can use the
childElementCount
property in the DOM element in JavaScript.
Let's say we have a div
element with some paragraph
elements inside it like this,
<div>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
<p>I'm a Paragraph</p>
</div>
Now let's get the count of the child paragraph
elements using the childElementCount
property in the div
element.
// get reference to the div element
const div = document.querySelector("div");
// get the length of children
// inside the div element
const lengthOfChildren = div.childElementCount;
console.log(lengthOfChildren); // 13
See this example live in JSBin.