[英]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". 我正在尝试选择并单击类“ .foo”中不包含类“ .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
: 您可以尝试使用
querySelectorAll
:
var inputs = document.querySelectorAll('.foo:not(.bar)');
Or as you have jquery
in your tags: 或在标签中包含
jquery
时:
$('.foo:not(.bar)').each( function() {
$( this ).click();
});
You can use the .filter()
function to first select all foo
s without bar
s: 您可以使用
.filter()
函数首先选择所有不带bar
的foo
:
CSS CSS
.foo, .bar{
padding:20px;
font-weight:bold;
}
jQuery 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 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.