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!
You have 3 div with the class parent. So I think you have to use a querySelectorAll(‘.parent’) and a loop after. Someting like this maybe
Your snippet will work for only one div.
parents
variable will store an array of all DOMs withclass='parent'
and you’ll need to loop over it:querySelector only returns the first matching element. You need to use querySelectorAll together with a loop: