How can I use getElementsByClassName with jQuery selector :not() selector

7.8k Views Asked by At

I'm trying to select and click on elements with the class ".foo" that do not contain the class ".bar".

I'd like to use code like this but it isn't working:

var inputs = document.getElementsByClassName('foo:not(bar)'); 
for(var i=0; i<inputs.length;i++) { 
    inputs[i].click(); 
}

Thanks for help!

2

There are 2 best solutions below

3
On BEST ANSWER

You can try to use querySelectorAll:

var inputs = document.querySelectorAll('.foo:not(.bar)'); 

Or as you have jquery in your tags:

$('.foo:not(.bar)').each( function() {
    $( this ).click();
});
0
On

You can use the .filter() function to first select all foos without bars:

JSFiddle

CSS

.foo, .bar{
    padding:20px;
    font-weight:bold;
}

jQuery

// get all foos and begine filtering
$('.foo').filter(function(){

    // show what class each div has
    $(this).text($(this).attr('class'));

    // translates into: IF bar not exist then return this element
    return !$(this).hasClass('bar');

// color the divs yellow
}).css('background-color','yellow');

HTML

<div class='foo'></div>
<div class='foo bar'></div>
<div class='foo bar'></div>
<div class='foo'></div>
<div class='foo'></div>
<div class='foo bar'></div>
<div class='foo'></div>
<div class='foo bar'></div>