tags:

views:

40

answers:

2

How can I detect the position of a specific item in the list ?

I have the following list:

<ul>
  <li>
  <li>
  <li class="current">
  <li>
</ul>

I need to know in which position the current item is. In this case the result should be 3.

thanks

A: 

You can use:

$("ul li.current").index() + 1;

Noe that this is not the accepted answer in the other question, the situation is different when dealing with siblings. .index() (without arguments) gives the sibling-index, which is all you need here.

Edit: just re-read the question, this is 0-based so it'd result in 2 not 3, just add 1 to the .index() result if you're after 1-based numbering.

Nick Craver
will this work? I was under the impression you'd have to do: $("ul li").index(".current");??
Thomas Clayson
@Thomas - A few new overloads were added in jQuery 1.4, with no arguments you can just get the index amongst your siblings :)
Nick Craver
fair enough. thanks. :)
Thomas Clayson
it always returns "-1" ... I'm sure the selector is correct: $("ul li.pager-current").index(); what am I doing wrong ? I'm sure it exists. I.e. length gives 1 (it is detected)
Patrick
It worked by doing this: $(".pager").index($(".pager-current"));
Patrick
A: 

.index()

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Adam Matan