Reputation: 73908
Lets imagine I have the following HTML code.
I need to find the position within the LI elements for the LI which has the class focus applied.
In this example the result should be 2 (if at 0 index). Any idea how to do it?
<ul class="mylist">
<li>Milk</li>
<li>Tea</li>
<li class="focus">Coffee</li>
</ul>
Upvotes: 2
Views: 1668
Reputation: 253308
While you've already accepted an answer to your question, I thought I'd put together a simple index()
method for HTMLElement
s:
HTMLElement.prototype.index = function () {
var self = this,
parent = self.parentNode,
i = 0;
while (self.previousElementSibling){
i++;
self = self.previousElementSibling
}
return this === parent.children[i] ? i : -1;
}
var focus = document.querySelector('li.focus'),
i = focus.index();
console.log(i); // 2
References:
Upvotes: 3
Reputation: 3366
In jQuery, you should be able to get it, via index
. With classes, you could run into issues, when having multiple of them.
I prepared a Plunker, where you can see a solution to the problem.
Upvotes: 1
Reputation: 1063
the expanded version (jquery) would be
$(document).ready(function(){
$('li').each(function(){
var cls=$(this).attr('class');
if(cls=='focus'){
alert($(this).index());
}
});
});
Upvotes: 0
Reputation: 32581
Use .index()
var index = $('.focus').index();
Specific list
$('.mylist .focus').index()
Upvotes: 2