[英]How can I use getElementsByClassName with jQuery selector :not() selector
我正在嘗試選擇並單擊類“ .foo”中不包含類“ .bar”的元素。
我想使用這樣的代碼,但是它不起作用:
var inputs = document.getElementsByClassName('foo:not(bar)');
for(var i=0; i<inputs.length;i++) {
inputs[i].click();
}
感謝幫助!
您可以嘗試使用querySelectorAll
:
var inputs = document.querySelectorAll('.foo:not(.bar)');
或在標簽中包含jquery
時:
$('.foo:not(.bar)').each( function() {
$( this ).click();
});
您可以使用.filter()
函數首先選擇所有不帶bar
的foo
:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.