tom91136
tom91136

Reputation: 8962

jQuery filter class that contains certain value

in jQuery, how do i filter all contents that contain certain class?

HTML:

<div class='item 10'>10</div>
<div class='item 20'>20</div>
<div class='item 30'>30</div>
<div class='item 40'>40</div>
<div class='not-an-item 50'>50</div>

what i've tried:

var classList = $(".item").attr('class').split(/\s+/);
if(classList[1] == '10' || lassList[1] == '30'){
    $(".item").hide();

}

correct output:

<div class='item 20'>20</div>
<div class='item 40'>40</div>
<div class='not-an-item 50'>50</div>

Upvotes: 2

Views: 4045

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

function hideItem(target) {
    $('div.item').filter(function() {
        var num = parseInt( this.className.split(/\s/)[1], 10 );
        if(target instanceof Array) {
          return $.inArray(num, target) >= 0; 
        } else return num > target;  
    }).hide();
}
hideItem([10,30]); // will hide item with class 10 and 30 
                   // and you can give any number of class

But if you want to hide item with class > 20(suppose) then just call it like;

hideItem(20);

Upvotes: 2

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You can use the .has() method or the .not() method to reduce the set of elements. With .has() you keep all elements that match a certain selector, while .not() keep all elements that doesn't match the selector.

For more advanced filtering, your can use the .filter() method.

If I understand your question correctly, you could use .filter() with a filtering-function. Something like this:

$(".item").filter(function() {
   return !($(this).hasClass("10") || $(this).hasClass("30"));
}).hide();

Upvotes: 7

Vinayak Phal
Vinayak Phal

Reputation: 8919

You can try like this..

$("div.item").hide();
$("div.item").not('div.10, div.30').show();

FIDDLE DEMO

Upvotes: 1

Related Questions