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!

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

  1. 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

    const parents = document.querySelectorAll(".parent");
    for (let i = 0; i < parents.length; i++) {
      if (parents[i].childElementCount > 5) {
      cityLocationTitle.classList.add('.reduce-size');
    }
    }
    
    Reply
  2.   const parents = document.querySelectorAll(".parent");
    
    parents.forEach(el => {
     if(el.childNodes.length > 5){
       el.classList.add('.reduce-size');
     }
    });
    
    Reply
  3. Your snippet will work for only one div. parents variable will store an array of all DOMs with class='parent' and you’ll need to loop over it:

    $('.parent').each(function(){
            // your code snippet
     });
    
    Reply
  4. querySelector only returns the first matching element. You need to use querySelectorAll together with a loop:

    const parents = document.querySelectorAll(".parent");
    
    for (let parent of parents) {
      if (parent.childElementCount > 5) {
          console.log("do stuff here");
      }
    }
    <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>
    Reply

Leave a Comment