How Do I Find the Index of An Element Within an Array
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?
var index = $("ul li.selected").index();
Try it out: http://jsfiddle.net/xXT9r/
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/
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.
精彩评论