views:

127

answers:

3

Hello everyone,

how can i get order number of some element by javascript/jquery?

<ul>
 <li>Anton</li>
 <li class="abc">Victor</li>
 <li class="abc">Simon</li>
 <li>Adam</li>
 <li>Peter</li>
 <li class="abc">Tom</li>
</ul>

There is 3xli with abc class. Now I need to get order(sequence) number of Simon li.

Thanks in advance

+3  A: 

With Jquery's index() method

Sarfraz
It's a +1 without the question marks.
T.J. Crowder
@T.J. Crowder: Thanks for pointing that out :)
Sarfraz
A: 

if you want to get the 'global' index use

$('ul').find('li:contains(Simon)').index()

in case you want the index from abc-class use

$('li.abc').find('li:contains(Simon)').index()

Kind Regards

--Andy

jAndy
`$('li.abc').find('li:contains(Simon)').index()` would yield `-1`, it's not a *child* of `li.abc`, you need `.filter()` here instead of `.find()`. Even with filter though, the result is the same as the first method, you need to pass `.index()` a selector to get anything other than it's index inside the parent (regardless of class or any previous selector).
Nick Craver
A: 

You can do it like this using a selector with .index(), like this:

$('li:contains(Simon)').index('.abc'); //returns 1, it's 0 based
//Or this...
$('li').filter(':contains(Simon)').index('.abc'); //returns 1

Without the selector, you'd get 2, the index of the <li> in the parent overall, regardless of the class. You can view a quick demo here. Keep in mind it's a 0 based index, may need to + 1 the result for display in some cases, depends what you need it for.

Nick Craver