Curious Programmer
Curious Programmer

Reputation: 127

Count the number of <div> elements inside <li>

I need to know how many <div> elements are in each <li>. So something like that:

<ul>
   <li>
      <div> Some image 1 </div>
      <div> Some image 2 </div>
      <div> Some image 3 </div>
   </li>
   <li>
      <div> Some image 4 </div>
      <div> Some image 5 </div>
   </li>
   <li>
      <div> Some image 6 </div>
      <div> Some image 7 </div>
      <div> Some image 8 </div>
      <div> Some image 9 </div>
   </li>
</ul>

The output of the function:

First <li> has 3 <div>
Second <li> has 2 <div>
Third <li> has 4 <div>

Upvotes: 0

Views: 2398

Answers (4)

gdoron
gdoron

Reputation: 150253

var lengths = $('li').map(function(){
    return $(this).find('div').length;
}).get();

Live DEMO

Comments:

// Make an array when the input for every iteration is a <li>
$('li').map(

// Every element in the array is the amount <div>s inside the current <li>
    return $(this).find('div').length;

// Produce the arry.
.get();

If you want to produce something similar to what you want easily:

$('li').each(function() {
    var length = $(this).find('div').length;
    $('<div> ' + length + ' li has ' + length + 'divs </div>').appendTo('#output');
});​

Live DEMO

Output:

3 li has 3divs
2 li has 2divs
4 li has 4divs

Upvotes: 6

Paul
Paul

Reputation: 141839

$('li').each(function(i){
    console.log('<li> ' + i + ' has ' + $(this).children('div').length + 'divs');
});

Upvotes: 1

j08691
j08691

Reputation: 207901

$('li').each(function() {
    console.log($('div', this).length);
});​

jsFiddle example.

Upvotes: 1

Ry-
Ry-

Reputation: 224904

Given a jQuery object representing your <li>, item, you can find out the number of <div>s that it contains just by doing:

item.find('div').length

But if you'd like a function with that exact output, you'll need a number → English library. Or, if you'll have exactly three, get your <ul> as list and do this:

var items = list.find('li');

'First <li> has ' + items.eq(0).find('div').length + ' <div>';
'Second <li> has ' + items.eq(1).find('div').length + ' <div>';
'Third <li> has ' + items.eq(2).find('div').length + ' <div>';

Upvotes: 2

Related Questions