2

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);
});

4 Answers 4

4

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

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

Comments

2

The problem is you need to limit the scope of the element look up to the desired parent element

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

Another version

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

Demo: Fiddle

Comments

2

This would require some extra work to show the number of childs in a more elegan way, but it should be enough to understand the idea

$(".parent").each(function(index){
    var $this = $(this);
    var numChilds = $this.find(".child").length;
    $this.append("<span>" + numChilds + "</span>");
});

Comments

1

This code will help you to get number of children separately for each parent div :-

  $(document).ready(function () {   
                      $(".parent").each(function (i)  {  
                                $(this).children().length;
                            });
                      });

Try this hope this may help you.Vote

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.