2

I was wondering how to count all the list items inside a div.

<ul class="menu">
    <li><a href="#">Home</a>
    </li>
    <li><a href="#">Contact</a>
    </li>
    <li><a>Information</a>
        <ul>
            <li><a href="#">History</a>
            </li>
            <li><a href="#">Present</a>
            </li>
            <li><a href="#">Future</a>
            </li>
        </ul>
    </li>
    <li><a>Tutorials</a>
        <ul>
            <li><a href="#">HTML/CSS</a>
            </li>
            <li><a href="#">Javascript</a>
            </li>
            <li><a href="#">Jquery</a>
            </li>
            <li><a href="#">PHP</a>
            </li>
        </ul>
    </li>
    <li><a href="#">Structure</a>
    </li>
</ul>

How do I count all the list elements inside ul class=menu? And not the list items who are in a deeper UL.

What I mean is how to count Home, Contact, Information, Tutorials, Structure, and not the list elements who are inside these I just mentioned.

Of course I did some research but couldn't find the correct answer. Here is somewhat of a duplicate: jQuery: Count number of list elements?

Community
  • 1
  • 1
Rien
  • 398
  • 2
  • 12
  • 37
  • The question specifically states the asker DOES NOT want the LI nested within any UL other than UL.menu – El Guapo Dec 18 '13 at 17:24

2 Answers2

9

Use the > child selector:

$('ul.menu>li').length

Or .children():

$('ul.menu').children('li').length
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • Thank you very much, this is my answer. I used the function size but that didnt work out for me. But what is the > arrow for? i haven't seen it being used in CSS? Sorry, here to learn not to copy paste – Rien Dec 18 '13 at 17:24
  • 2
    @KrijnvanderBurg You’ll find plenty of information in the docs: https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors – David Hellsing Dec 18 '13 at 17:25
  • > means the direct decendant – El Guapo Dec 18 '13 at 17:25
  • just as an alternative for newer browsers and without the use of jQuery: `document.querySelectorAll('ul.menu > li').length` works the same – tombul Dec 18 '13 at 17:35
2

The other question is in jQuery, so I answer for jquery, try this to count your li elements

var count = $('ul.menu').children('li').length;

DEMO

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171