Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter undesired elements with jQuery

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

like image 247
Eduard Avatar asked Jan 16 '23 18:01

Eduard


1 Answers

$('.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');
like image 114
gdoron is supporting Monica Avatar answered Jan 19 '23 07:01

gdoron is supporting Monica