Javascript Retrieve DOM element according to the number of its children

I need some help on the following:

I want to get the DOM elements that have more than 5 children and add a class name to only those elements. For example,

<div class="parent">
    <span>child</span>
    <span>child</span>
    <span>child</span>
</div>

<div class="parent">
    <span>child</span>
    <span>child</span>
    <span>child</span>
    <span>child</span>
    <span>child</span>
    <span>child</span>
</div>

<div class="parent">
    <span>child</span>
    <span>child</span>
</div>

In this case I’d like to add a class name to the second div above that has 6 children spans.

I’ve tried the following:

const parents = document.querySelector(".parent");

if (parents.childElementCount > 5) {
    parents.classList.add('.reduce-size');
}

But no luck.

Please help.

Thanks!

18 thoughts on “Javascript Retrieve DOM element according to the number of its children”

Leave a Comment