如何通过一个类查找元素,但使用JQuery排除其他元素

时间:2017-01-30 20:25:18

标签: javascript jquery html css

我有多个元素,类似

<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');

但我得到了所有元素

3 个答案:

答案 0 :(得分:11)

您没有正确使用:not选择器。 您可以使用not方法或:not选择器为此方案选择元素。

  $('.target-class:not(.exclude-class)');  // :not selector

$('.target-class').not('.exclude-class'); // .not method

<强> Check Fiddle

答案 1 :(得分:3)

您可以使用.not()方法:

&#13;
&#13;
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;
&#13;
&#13;

答案 2 :(得分:2)

您的查询语法不正确。它应该如下:

var elements =$find('.target-class:not(.exclude-class'));

var elements =$find('.target-class').not('.exclude-class');