1

I have an unordered list with sub menus.

I have an unordered list and i want to print the number of child list items each list item contains , however, the function I wrote only returns 0.

If I replace $(this) with a class or ID then it works fine, however, it then prints the same number for every list item, and I need it to be dynamic, returning the .length or .size() of each individual list item.

Can you please guide me in the right direction? :)

/*atomic mass counter*/
$(document).ready(function(mass){

var atomic = $(this).parent('li').length;

$('.atom').html(atomic);

});

the class .atom is a child of each list item so the list looks something like this:

<ul>
  <li>
    <div class='atom'></div>
    <ul>
      <li><div class='atom'></div></li>
      <li><div class='atom'></div></li>
    </ul>
  </li>
  <li><div class='atom'></div></li>
  <li><div class='atom'></div></li>
  <li><div class='atom'></div></li>
</ul>

Here's a JSfiddle: https://jsfiddle.net/6gzau45r/1/

1
  • 1
    what are the expected results? Most in example have no sub menu. Not clear what you are wanting to measure Commented Mar 31, 2015 at 17:22

2 Answers 2

1

This answer uses jQuery's .each() method to iterate all li elements and uses .find() method to count how many elements (and child elements) with class .atom each li has.

/*atomic mass counter*/
$(document).ready(function (mass) {

    $("li").each(function () {

        var atomic = $(this).find('.atom').length;

        $(this).find('.atom').first().html(atomic);

    });

});

Fiddle

The atomic count is set to the first .atom element of each li.

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

Comments

0

You have to look the descendents by using .children(). Your solution may look similar to:

$(document).ready(function(mass){
    // For each atom div
    $('.atom').each(function() {
        // Calculates the children li
        $(this).html($(this).parent().children('ul').children('li').size());
    });    
});

Here is a FIDDLE:

https://jsfiddle.net/6gzau45r/6/

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.