简体   繁体   中英

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

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!

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();
});

You can use the .filter() function to first select all foo s without bar s:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM