tags:

views:

147

answers:

4

Hi,

I have a list like this:

<ul>
    <li class="pageItem">1</li>
    <li class="pageItem">2</li>
    <li class="pageItem current">3</li>
    <li class="pageItem">4</li>
    <li class="pageItem">5</li>
</ul>

I want to calculate the list item position of .current. In this case it would be 3.

Just to make things clear: I don't want the X & Y position of the element. Just what number in the line it has.

Thanks!

+4  A: 
$('li.pageItem').index($('li.current')[0]);

will return 2, just add +1 if you want the index starting from 1.

David
This is going to be very slow as elements matching two selectors will have to be found.
RaYell
+1, better than mine
stereofrog
I'll use this one then, many thanks!
Fred Bergman
A: 
$('ul li.pageItem').each(function(i) {
 if($(this).hasClass('current')) //i is your index
});

Edit: index() is probably a better way to do it (see other answer)

Soufiane Hassou
A: 

$('li.current').prevAll().length will give you the position of selected item in the list. Notice that this value will be zero-based so if you want this to be one-based add +1 to this value.

RaYell
lenght returns the length of the jQuery array (matches), not position. See: http://docs.jquery.com/Core/index
David
I know what it does. You should check out what `prev()` returns. It will give you all preceding li elements and their count is what he is looking.
RaYell
you mean prevAll() I assume :)
David
Yeah, `prevAll()`.
RaYell
+1  A: 
  $("li.current").prevAll("li").size()

// edit: actually, David's answer is better, since it shows more directly what we're after. The only thing, [0] is not needed, according to http://docs.jquery.com/Core/index, "if a jQuery object is passed, only the first element is checked.", that is, simply use

 position = $("li").index($(".current"))
stereofrog
This is perfect, thanks!
Fred Bergman
You should use `length` instead of `size()` as it's faster.
RaYell
no I shouldn't. size() is more portable and looks nicer.
stereofrog
No, you're wrong. Check jQuery docs http://docs.jquery.com/Core/size
RaYell