0

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 Answers 3

7
var index = $("ul li.selected").index();

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. +1 for the jsfiddle example, which works perfectly.
3

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/

3 Comments

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); jsfiddle.net/xXT9r/3
Yes you are right - I updated it so it works now and will add your sample.
Yes, looks like you've got it now.
2

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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.