Header 1
...">

Use jQuery to count the number of divs 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 elements .itemare in each <section>. This is currently trying, but it does not give me the correct number:

$('section.group').each(
  function() {
    alert($(this).length);
  }
);
+3
source share
8 answers

Try:

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

[Working example]

or

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

[Working example]


You repeated the sections, but you didn’t have enough elements with the class item:)


Useful links:

+12
source

You need to look at ".item" in the context of this. it has a length of one because it = 'section.group'

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

See the Context Selector heading here: http://api.jquery.com/jQuery/

+1

:

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

: http://jsfiddle.net/aXVqM/

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

, ... ,

+1

try it.

$('.change').click(function () {
     var lng = $(".item").length;
            $('.change ').height(function (index, height) {
                return (height * lng);
                //alert(height);
            });

     alert(lng);
        });

.change is a div class whose height or width you are changing you can check how to implement here: http://jsfiddle.net/sahilosheal/572WV/

+1
source

I have a name for the name of the second section, see the demo here:

$('section').each(function() {
    var numItems = $('.group').children('div.item').length;

    alert(numItems+''); 
});

$('section').each(function() {
    var numItems = $('.group1').children('div.item').length;

    alert(numItems+''); 
});

Watch this demo .

0
source
$(".group").find(".item").length

This is the simplest single line solution.

0
source

All Articles