Jquery: Check How Many Instances of Class in Element

I have code that looks like this:

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

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

What I want to do with jquery, is find any element with class “parent”, and remove that element if it has only one instance of the “child” element (or less). If it has 2 or greater, it does nothing.

So, in regards to the code above, I plan on adding an inline style of “display:none;” on the first “parent” div since only has one instance of the “child” element.

What would be the trick to accomplishing this?

Cheers!
Ryan

Hi @casbboy, these days it can be easily accomplished without jQuery. Something like this:

var parents = document.querySelectorAll('.parent');
for(var i = 0; i < parents.length; i++) {
    var children = parents[i].querySelectorAll('.child');
    if (children.length < 2) {
        parents[i].style.display = 'none';
    }
}
2 Likes

You are awesome! Going to give this a try shortly.

Had yet to find out about a much simpler CSS solution which may work for you, the only downside is that you are hiding the only child, not actually the parent, which is what you asked for:

.child:only-child {
  display: none;
}

check it out!

or

let parents = document.querySelectorAll(‘.parent’);
for(var i = 0; i < parents.length; i++) {
if (parents[i].querySelectorAll(‘.child’).childElementCount < 1) {
parents[i].style.display = ‘none’;
}
}

Sorry made a mistake , it should be

let parents = document.querySelectorAll(‘.parent’);
for(var i = 0; i < parents.length; i++) {
if (parents[i].childElementCount < 1) {
parents[i].style.display = ‘none’;
}
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.