views:

96

answers:

4

Say I have html similar to the following

<ul>
  <li> hi </li>
  <li> hoi </li>
  <li> privyet </li>
  <li class="selected"> bonjour </li>
  <li> hallo </li>
</ul>

and I use jQuery to get all the li elements in the ul

$("ul li")

how can I get the index of the li element with the class selected within the jQuery array of li elements?

+3  A: 

With index: http://api.jquery.com/index/

Description: Search for a given element from among the matched elements.

// Text
$("ul li.selected").index("ul li");

Thx patrick

// jQuery object
$('ul li.selected');
var index = $("ul li").index(elem);

// search Within siblings
$("ul li.selected").index();

All 3 demos: http://jsfiddle.net/xXT9r/4/

Ghommey
Your answer doesn't work: http://jsfiddle.net/xXT9r/1/
patrick dw
I updated my answer 2 mins ago. It is fixed isn't it?
Ghommey
Ghommey - I'm talking about your updated answer. I gave you a link to test it. I think you were thinking of this: `var elem = $('ul li.selected');var index = $("ul li").index(elem);` http://jsfiddle.net/xXT9r/3/
patrick dw
Yes you are right - I updated it so it works now and will add your sample.
Ghommey
Yes, looks like you've got it now.
patrick dw
A: 

how about using index()? http://api.jquery.com/index/

limc
+6  A: 
var index = $("ul li.selected").index();

Try it out: http://jsfiddle.net/xXT9r/

patrick dw
Good answer. +1 for the jsfiddle example, which works perfectly.
Jamiec
@Jamiec - Thanks for the + . :o)
patrick dw
+2  A: 

To me, if you've already done the $("ul li"), then you want to avoid doing it again (if you haven't already done it, I'd definitely go with patrick's approach). Let's say you stored that jQuery object as items. You'd do this:

var pos = items.index(items.filter(".selected"));

Fiddle: http://jsfiddle.net/Nk3Aj/ (blatantly stole patrick's and updated :-) )

This uses the second variant of index:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

Again, this is useful if you've already done the $("ul li") part.

T.J. Crowder
T.J. - Good point. The question did imply that it is starting with the entire set. +1
patrick dw