Kez Kez - 3 months ago 7
jQuery Question

How to count elements of the same class until other class with jQuery?

How can I count the number of

cv_item
until next
cat_header_holder


My attempt is below, however this merely outputs 0 for each
cat_header_holder


Example HTML:

<div class="cat_holder">

<div class="cat_header_holder">
<h1>Header <span class="cv_cat_count"></span></h1></div>

<div class="cv_group"> <a class="cv_item" href></a> </div>
<div class="cv_group"> <a class="cv_item" href></a> </div>

<div class="cat_header_holder">
<h1>Header <span class="cv_cat_count"></span></h1></div>

<div class="cv_group"> <a class="cv_item" href></a> </div>
<div class="cv_group"> <a class="cv_item" href></a> </div>
<div class="cv_group"> <a class="cv_item" href></a> </div>
<div class="cv_group"> <a class="cv_item" href></a> </div>

<div class="cat_header_holder">
<h1>Header <span class="cv_cat_count"></span></h1></div>

<div class="cv_group"> <a class="cv_item" href></a> </div>


</div>


jQuery:

$('.cat_header_holder').each(function () {
var count = $(this)
.closest(".cv_group")
.nextUntil("div:has(.cat_header_holder)")
.find(".cv_item")
.length;

$(".cv_cat_count").text(count);
});

Answer

Like this:

 $('.cat_header_holder').each(function() {
   var count = $(this).nextUntil('.cat_header_holder').find(".cv_item").length;
   $(this).find(".cv_cat_count").text(count);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat_holder">
  <div class="cat_header_holder">
    <h1>Header <span class="cv_cat_count"></span></h1></div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
  <div class="cat_header_holder">
    <h1>Header <span class="cv_cat_count"></span></h1></div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
  <div class="cat_header_holder">
    <h1>Header <span class="cv_cat_count"></span></h1></div>
  <div class="cv_group">
    <a class="cv_item" href></a>
  </div>
</div>
You were adding .closest which traverses up the DOM.