Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JavaScript - Counting child elements in multiple parent elements

I'm creating a directory of apps, each of which has it's own comments which are hidden until the user opens them. I'd like to show the number of comments that each app currently contains but I can only get it display the total number of comments on the page (See JSFiddle: http://jsfiddle.net/9M4nw/2/ for a basic example). Ideally it should display 2 in the top box and 4 in the bottom box. I thought I might need to use an array or something along those lines?

Here is my code:

HTML

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

jQuery

$(".parent").each(function(index){
    var numChilds = $(".child").length;
    $(".parent").append(numChilds);
});
like image 474
TJ152 Avatar asked Aug 01 '26 10:08

TJ152


1 Answers

You have to select the current HTML element (with class parent). Then, you will use it in selecting the length of elements with class .child and the html for .counter.

Using $(this) you can select the current HTML element from each() function. Corrected code:

$(".parent").each(function(){
    var numChilds = $(".child", $(this)).length;
    $(".counter", $(this)).html(numChilds);
});

JSFIDDLE

like image 178
Ionică Bizău Avatar answered Aug 03 '26 00:08

Ionică Bizău



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!