sachinM
sachinM

Reputation: 128

Can I use 'not' and 'contains' filter together in jQuery

I want to apply 'not' and 'contains' filter together to filter element in HTML.

consider I have element as follows ,

<tr class="filter" value="value1" name="something1">
<tr class="filter" value="value1" name="something2">
<tr class="filter" value="value3" name="something3">
<tr class="filter" value="value1" name="something4">

and I want to apply filter as

$(".filter").not("[value*='value1']").contains('something4')

But it does not work. Please help me, Thanks.

Upvotes: 2

Views: 110

Answers (2)

Jai
Jai

Reputation: 74738

I would suggest you to use .filter() method instead:

var filtered = $(".filter").filter(function(){
    return $(this).attr('value') !== 'value1' && $(this).attr('name') === 'something4'
});
filtered.css('color', 'red');

with attribute selectors (Not recommended):

$(".filter:not([value*='value1']):contains('something4')")

As per your comment:

4'th one is my target

Then:

You don't have to check for negative values but you should go for the equality:

var filtered = $(".filter").filter(function(){
    return $(this).attr('value') === 'value1' && $(this).attr('name') === 'something4'
});
filtered.css('color', 'red');

or:

$(".filter[value='value1'][name='something4']").css('color', 'red');

Upvotes: 4

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can do this in a single selector, however performance will be better using filter() as noted in Jai`s answer.

$(".filter:not([value*='value1']):contains('something4')")

Also note that given your HTML example, this selector will not match anything as you exclude the element with the something4 text with the :not.

Upvotes: 1

Related Questions