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
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