How to filter undesired elements with jQuery

断了今生、忘了曾经 提交于 2019-12-23 12:46:30

问题


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');


来源:https://stackoverflow.com/questions/10466940/how-to-filter-undesired-elements-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!