Get the number of children from one instance of a class

I am setting up a tumblr blog, and I want to apply certain styles and rules depending on the number of photos present in the photoset. I am not sure how to get the number of children present in each message when each column has the same class. If this is the code that tumblr generated:

<div class="photoset">
     <img />
     <img />
</div>

<div class="photoset">
     <img />
     <img />
     <img />
</div>

How do I get jQuery to return the number of elements in the first and second instances (i.e. 2 and 3)?

I tried using $('.photoset img').length();, and this gives me the total number of all elements present (i.e. 5 in this case).

Any help would be greatly appreciated!

Cheers, Scott

+3
source share
5 answers

, , , :

$(".photoset").each(function(index, elem) {
    var numImages = $(this).find("img").length;
    // do whatever processing you wanted to with numImages here
});

, :

var imgCountArray = $(".photoset").map(function() {
    return($(this).find("img").length)
}).get();
+7

,

var imgCounts = [];

$('.photoset').each (function () {
  imgCounts.push($(this).find('img').length);
});

,

imgCounts[0] = 2 //first divs img count
imgCounts[1] = 3 //second divs img count
+2

There are several ways to do this.

Firstly, you can use .each()to cycle through each .photoset:

$('.photoset').each( function() {
   var num = $(this).find('img').length;
   // Do something based on num
});

Or, use .eq()or :eq()to select a specific:

var num = $('.photoset:eq(1) img').length;

var num = $('.photoset').eq(1).find('img').length;

+1
source

you can use:

$(".photoset").each(function(i, photoset) {
  photoset = $(photoset); 
  var numImages = photoset.children().length;
  // or var numImages = photoset.find("img").length; for only images

  if (numImages === 2) {
    // your code
  }
  if (numImages === 3) {
    // your code
  }

  // or just comparing whether greater or lower
  if (numImages > 2) {
    // your code
  }
});
+1
source
$('.photoset:first img').length

and

$('.photoset:last img').length
0
source

All Articles