santa
santa

Reputation: 12512

Count elements with empty attribute

I need to loop through me elements and count how many of them have an empty data-v attribute:

<div data-v="" style="height: 0px"></div>

I've tried this bit doesn't seem to work:

$(".myEm").each(function() {
    var cnt = $(this).find("div[data-v!='']").length;
});

What am I missing?

Upvotes: 0

Views: 160

Answers (1)

ADyson
ADyson

Reputation: 61914

Your selector is looking for elements which don't have an empty attribute. Here's a demo showing some of each type, and one query with a selector using "not" (!) and one without it, and the resulting counts:

$(function() {
  $(".myEm").each(function() {
    var cnt = $(this).find("div[data-v!='']").length;
    console.log(cnt);
    var cnt2 = $(this).find("div[data-v='']").length;
    console.log(cnt2);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myEm">
  <div data-v="" style="height: 0px "></div>
  <div data-v="" style="height: 0px "></div>
  <div data-v=" " style="height: 0px "></div>
  <div data-v=" " style="height: 0px "></div>
  <div data-v=" " style="height: 0px "></div>
</div>

So you need to amend your code or markup as suits you, to get the result you intended.

Upvotes: 1

Related Questions