How to filter undesired elements with jQuery

2019-06-24 00:38发布

问题:

lets take for example two divs,

<div class="main right"></div>
<div class="main"></div>

And this jQuery snippet, as it follows:

$('.main').css('background-color','red');

This will change both divs background-color to red, as normal. I'd like to know how to change that color for the divs that have only "main" as class, not "main right",

回答1:

$('.main:not(.right)').css('background-color','red');

Or:

$('.main').not('.right').css('background-color','red');

If had to more complicated conditions it can be done with filter function:

$('.main').filter(function(){
    return $(this).data('value') == 2 && this.innerHTML.length < 50;
}).css('background-color','red');

It will filter out the result of .main and maintain only element which their data-value is 2 and their innerHTML.length < 50.


If you don't know what other classes could be to main but you want the elements which has only the main class.

$('.main').filter(function(){
    return $.trim(this.className) == 'main';
}).css('background-color','red');


回答2:

use the 'not()' selector.

$('.main:not(.right))
or like: $('.main').not('.right')



回答3:

It looks to me that you want to verify that "main" is the only class before you apply the style. You can do this with a quick regex test:

$('.main').filter(function(){
    return /^\s*main\s*$/.test(this.className);
}).css('background-color','red');