计算不包含某个类的元素

时间:2016-01-17 17:39:02

标签: jquery

如何计算没有类.extra?

的元素.em



var cnt = $('.em').not('.extra').length;
console.log(cnt);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="em">
  <div class="header">aaa</div>
  <ul>nnn</ul>
</div>

<div class="em">
  <div class="header">aaa</div>
  <div class="extra">eee</div>
  <ul>nnn</ul>
</div>

<div class="em">
  <div class="header">aaa</div>
  <ul>nnn</ul>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:4)

您使用.em类来否定.extra个元素。由于.em元素都没有类.extra,因此所有元素都被选中。

一种选择是将:not():has() selector合并:.em:not(:has(.extra))

&#13;
&#13;
var cnt = $('.em:not(:has(.extra))').length;
console.log(cnt);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="em">
  <div class="header">aaa</div>
  <ul>nnn</ul>
</div>

<div class="em">
  <div class="header">aaa</div>
  <div class="extra">eee</div>
  <ul>nnn</ul>
</div>

<div class="em">
  <div class="header">aaa</div>
  <ul>nnn</ul>
</div>
&#13;
&#13;
&#13;