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?
var xx = $('ul li#end').length;
<li id="end">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()?
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.
.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
<font color='#464646'>$('ul li').length - </font><font color='#464646'>$('ul li#end').index();
This topic is now closed. New replies are no longer allowed.