...">

How to filter unwanted elements using jQuery

allows you to take, for example, two divs,

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

And this jQuery snippet as follows:

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

This will change both div-colors to red as usual. I would like to know how to change this color for divs that have only "main" as a class, and not "main right",

+4
source share
3 answers
 $('.main:not(.right)').css('background-color','red'); 

Or:

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

If for more complex conditions this can be done using the filter function:

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

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


If you do not know that other classes may be main , but you need elements that only have the main class.

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

use the "not ()" selector.

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

+1
source

It seems to me that you want to check that the "main" is the only class before applying the style. You can do this with a quick regular test:

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

Source: https://habr.com/ru/post/1410924/


All Articles