phantom007 — 2012-01-24T11:50:04-05:00 — #1
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>
felito — 2012-01-24T12:07:52-05:00 — #2
It shows 6 because the first is the index zero
phantom007 — 2012-01-24T12:10:30-05:00 — #3
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()?
aussiejohn — 2012-01-24T15:58:01-05:00 — #4
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
phantom007 — 2012-01-24T23:43:30-05:00 — #5
Thanks for the detailed explanation.
phantom007 — 2012-01-25T00:11:44-05:00 — #6
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.
aussiejohn — 2012-01-25T00:13:56-05:00 — #7
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();
phantom007 — 2012-01-25T00:25:36-05:00 — #8