Mark
Mark

Reputation: 8431

jQuery filter using CSS class/subclass

Suppose I have this code:

<div class="notes">
    <div class="note">
         <div class="inner-content like"></div>
    </div>
    <div class="note">
         <div class="inner-content unlike"></div>
    </div>
    <div class="note">
         <div class="inner-content unlike"></div>
    </div>
</div>

What I want is to filter the like and unlike subclass.

I tried this code but no luck:

$("div.notes").filter(".note.note-inner>.like").hide();

The div that has like subclass is not hiding.

UPDATE


I want to hide the element with .note class not the one with the .inner-note like.

Upvotes: 2

Views: 4412

Answers (3)

Michael Coker
Michael Coker

Reputation: 53674

you don't have a .note-inner and your selectors are wrong. .note.note-inner would be an element with class="note note-inner". And .notes is only 1 element, so $.filter() isn't going to find any other elements or the children in .notes

I think you meant $("div.notes").find(".note > .like").hide(); but you could also just do $('div.notes > .note > .like').hide() with or without the direct descendent selectors - they aren't necessary for the markup you shared.

If you want to remove a .note if it has a .like as a child, use $("div.notes").find(".like").closest('.note').hide();. That will find a .like inside of .notes, then find the closest ancestor with class .note and hide it.

$("div.notes").find(".like").closest('.note').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notes">
  <div class="note">
         <div class="inner-content unlike">unlike</div>
    </div>
    <div class="note">
         <div class="inner-content like">like</div>
    </div>
    <div class="note">
         <div class="inner-content unlike">unlike</div>
    </div>
    <div class="note">
         <div class="inner-content unlike">unlike</div>
    </div>
</div>

Upvotes: 7

luly
luly

Reputation: 614

You can try this

 $(".note > .inner-content.like").hide();

 $(".note > .inner-content.like").show();

and

 $(".note > .inner-content.unlike").hide();

 $(".note > .inner-content.unlike").show();

I created a JSfiddle showing the filters with button toggles https://jsfiddle.net/jmbm2myu/3/

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

.filter() applies to the elements you are going to filter, as such you want to apply it to the <div class="inner-content .."></div> elements:

$("div.notes > .note > .inner-content").filter(".like").hide();

Or simply

$("div.notes > .note > .inner-content.like").hide();

For removing the .note element you can just get the parent:

$("div.notes > .note > .inner-content.like").parent(".note").hide();

Upvotes: 1

Related Questions