tillinberlin
tillinberlin

Reputation: 439

jQuery: hide parent if there's only 2 child objects (or less)

I need to hide the parent object if it only contains two or less child objects. The szenario is: I have events listed as <div class="event"> and every event has a url and a title. Additionally every event can have participantsof various types – or none. If there's no participants listed, I would want jQuery to remove the entry.

What I have so far is this:

// Hide empty events
if(($(".event").children().length)<3) { 
$(this).hide();
}

But that doesn't have any impact.

On a different content teype I use this to check (and remove) empty parents:

$("description:empty").parent().hide();

I would love to apply this one liner to my "event-task" but the data structure / the xslt transformation is too different to apply the same simple function. Any pointers welcome!

Upvotes: 1

Views: 59

Answers (2)

charlietfl
charlietfl

Reputation: 171690

You need to check instances of event otherwise you will have a collection of children of all events

You could loop over them all using $.each or use filter()

$(".event").filter(function(){
    return $(this).children().length < 3;
}).hide();

Upvotes: 3

Islam Zedan
Islam Zedan

Reputation: 656

you must to loop on your elments to check them here is my code to do that

$(document).ready(function(){
$(".event").each(function(){
  if(($(this).children().length)<3) { 
    $(this).hide();
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="event" >
<span>1</span>
  <span>1</span>
  <span>1</span>
</div>
<div class="event" >
<span>1</span>
<span>1</span>
</div>
<div class="event" >
<span>1</span>
</div>
<div class="event" >
<span>1</span>
<span>1</span>
  <span>1</span>
  <span>1</span>
  <span>1</span>
</div>

Upvotes: 1

Related Questions