1

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).

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.