Graeme Bryson
Graeme Bryson

Reputation: 193

Counting specific children within parent div

I'm currently attempting to show a count for the number of images in a gallery (i.e "There are 'x' images in this gallery"). There's multiple galleries on each page as they're embedded in posts in a Wordpress feed.

On my localhost, I can actually get it to show a count, but it counts every image on the page, as if it's not being constrained to the parent div for counting.

Any input would be massively appreciated - http://jsfiddle.net/fvoLaad1/2/ or code below:

EDIT: Solved thanks to @Mohamed-Yousef and @Tom Millard - working version here http://jsfiddle.net/kuLsjLgg/

jQuery

jQuery(function($) {
  $('.iso-post').each(function(i) {
    var n = $('.gallery-item').length;
    $(".image-count").text("There are " + n + " images in this gallery.");
  });
});

HTML

<li class="iso-post">
    <span class="image-count"></span>
    <div class="post-content">
        <div class="gallery">
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
        </div>
    </div>
</li>

<li class="iso-post">
    <span class="image-count"></span>
    <div class="post-content">
        <div class="gallery">
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
            <figure class="gallery-item">IMG</figure>
        </div>
    </div>
</li>

Upvotes: 0

Views: 67

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you need to loop through each gallery to get the number of images in it

jQuery(function($) {
   $('.gallery').each(function(){
    var n = $(this).find('.gallery-item').length;
    $(this).closest('.iso-post').find(".image-count").text("There are " + n + " images in this gallery.");
   });
});

Working Demo

to get all images length just use

$('.gallery-item').length;

Upvotes: 2

Millard
Millard

Reputation: 1157

You need to use this to reference the current loop index, and find to locate the children.

jQuery(function($) {
  $('.iso-post').each(function(i) {
    var n = $(this).find('.gallery-item').length;
    $(this).find(".image-count").text("There are " + n + " images in this gallery.");
  });
});

Upvotes: 1

Related Questions