jQuery: Getting a count of LIs


I wanted to get a count of all the LIs until <li id=“end”>Test </li>

So the alert should prompt 7 instead of 12. I am trying the following code but does not seem to work. The code is prompting me 1. Can you pls help me?

<script src="jquery.js"></script>

		var xx = $('ul li#end').length;


	<li>Test </li>
	<li>Test </li>
	<li>Test </li>
	<li>Test </li>
	<li>Test </li>
	<li>Test </li>
	<li id="end">Test </li>
	<li>Test </li>
	<li>Test </li>
	<li>Test </li>
	<li>Test </li>
	<li>Test </li>						


It shows 6 because the first is the index zero

So even if I do

var xx = $(‘ul li#end’).index();

It shows 6.

  1. May I know why did you add the extra > after ul?
  2. Whats the difference between length and index()?


It shows 6 as JavaScript uses arrays whose index starts at 0 (as do many other C-based languages).

The extra “>” is a CSS selector that says “Only select the next element if it is a direct child” … in this case it’s saying “only select li#end if it is a direct child of ul”. Additionally in this example the immediate-child operator is superfluous as the <li> in question has an ID and <li>'s always need to be a direct child of a <ul>. In fact, in this example, because your <li> has an ID, you could even leave the "ul " part of the selector off completely.

The difference between [I].length[/I] and [URL=“http://api.jquery.com/index/”][I].index()[/I] is that .length is a native JavaScript property of Arrays. It will return the length of the array. So when you did your initial selection of $(“ul li#end”) jQuery was only returning one element, and thus the length property was 1.

.index() is a jQuery method that will return the index of an element relative to its sibling elements

Thanks for the detailed explanation.

Also, is there anyway to find out the total number of LIs after <li id=“end”>Test </li> ?

So it should be 5 in the above case.


Yeah, should be easy. You could get the index of #end and subtract if from the total.

So something like

[COLOR=#464646]$('ul li').length - [/COLOR][COLOR=#464646]$('ul li#end').index();


Thanks that works.