我有多个元素,类似
<li class="target-class exclude-class"></li>
<li class="target-class exclude-class"></li>
<li class="target-class"></li>
<li class="target-class"></li>
<li class="target-class"></li>
我想只在没有exclude-class的情况下才能找到带有target-class的元素。我试过了
var elements = $find('.target-class exclude-class:not');
但我得到了所有元素
答案 0 :(得分:11)
您没有正确使用:not
选择器。
您可以使用not方法或:not选择器为此方案选择元素。
$('.target-class:not(.exclude-class)'); // :not selector
或
$('.target-class').not('.exclude-class'); // .not method
<强> Check Fiddle 强>
答案 1 :(得分:3)
您可以使用.not()
方法:
var elements = $('.target-class').not('.exclude-class');
console.log(elements.length);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="target-class exclude-class">1</li>
<li class="target-class exclude-class">2</li>
<li class="target-class">3</li>
<li class="target-class">4</li>
<li class="target-class">5</li>
&#13;
答案 2 :(得分:2)
您的查询语法不正确。它应该如下:
var elements =$find('.target-class:not(.exclude-class'));
或
var elements =$find('.target-class').not('.exclude-class');