Henior
Henior

Reputation: 11

jQuery: How to count children within element with class

I have multiple 'div' elements with the same class 'column' and within each one I've got an unordered list 'ul' with class 'list' and elements 'li' with class 'item'.

The number of 'li.item' vary depends on different 'column'. How can I count the number of 'li.item' within a single 'column'?

I tried:

<div class="column">
<ul class="list">
<li class="item">item 1</li>
<li class="item">item 2</li>
<li class="item">item 3</li>
</ul>
</div>
<div class="column">
<ul class="list">
<li class="item">item 4</li>
<li class="item">item 5</li>
</ul>
</div>
<div class="column">
<ul class="list">
<li class="item">item 6</li>
</ul>
</div>

https://jsfiddle.net/u0hj58xe/

I wolud like to have: 3 , 2 , 1 insted of 6,6,6 (each div treated separately).

Upvotes: 1

Views: 2959

Answers (3)

Martin M
Martin M

Reputation: 465

Basically the same answer as the others, just without 'find' and 'closest'.

$('.column').each(function(){
var $this = $(this);
$($this).append($('.list .item', $this).length);
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82251

Your current code is targeting all ul elements. You Need To iterate over the ul elements and then find child elements in it. You can use elements context this to target the current ul in .each() along with traversing selector to find elements and append count info in div:

$('.list').each(function(){
  var $this = $(this);
  var items = $this.find('.item').length;
  $this.closest('.column').append(items);
});

Working Demo

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you need to use .each() to loop through columns

$('.column').each(function(){
  console.log($(this).find('.item').length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="column">
  <ul class="list">
    <li class="item">item 1</li>
    <li class="item">item 2</li>
    <li class="item">item 3</li>
  </ul>
</div>
<div class="column">
  <ul class="list">
    <li class="item">item 4</li>
    <li class="item">item 5</li>
  </ul>
</div>
<div class="column">
  <ul class="list">
    <li class="item">item 6</li>
  </ul>
</div>

Upvotes: 3

Related Questions