CLiown CLiown - 6 months ago 8
jQuery Question

Use jQuery to count the number of div's inside a div

I have the following output:

<section class="group">
<div class="header">Header 1</div>

<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>

</section>

<section class="group">
<div class="header">Header 2</div>

<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>

</section>


I want to use jQuery to tell me how many
.item
elements are in each
<section>
. Currently trying this, but it doesn't give me the correct number:

$('section.group').each(
function() {
alert($(this).length);
}
);

Answer

Try:

$('section.group').each(
  function() {
    alert($('.item', $(this)).length);
  }
);

[Working Example]

Or

$('section.group').each(
  function() {
    alert(($(this).find('.item')).length);
  }
);

[Working Example]


You were iterating over sections but you were missing to count elements with class item :)


Helpful Links: