Reputation: 2020
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!
Upvotes: 2
Views: 10516
Reputation: 53940
$("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"))
Upvotes: 1
Reputation: 70414
$('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.
Upvotes: 0
Reputation: 17750
$('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)
Upvotes: 0
Reputation: 108500
$('li.pageItem').index($('li.current')[0]);
will return 2, just add +1 if you want the index starting from 1.
Upvotes: 7