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>
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>
Share
Improve this question
edited Aug 12, 2013 at 11:27
GibboK
asked Aug 12, 2013 at 11:24
GibboKGibboK
74k147 gold badges451 silver badges674 bronze badges
3
-
@Cherniv you mean
index
– Rory McCrossan Commented Aug 12, 2013 at 11:26 -
@RoryMcCrossan i don't know about
index
in VanillaJS – Ivan Chernykh Commented Aug 12, 2013 at 11:27 -
I know, I was being facetious in the fact that
index
in jQuery makes this a 1-liner. – Rory McCrossan Commented Aug 12, 2013 at 11:28
5 Answers
Reset to default 4In pure JavaScript:
var index = 0;
var lis = document.getElementsByTagName('li');
for (var len = lis.length; index < len; ++index) {
if (lis[index].className.match(/\bfocus\b/)) {
break;
}
}
(fiddle)
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
JS Fiddle demo.
References:
Element.previousElementSibling
document.querySelector()
.
Use .index()
var index = $('.focus').index();
DEMO
Specific list
$('.mylist .focus').index()
DEMO
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.
the expanded version (jquery) would be
$(document).ready(function(){
$('li').each(function(){
var cls=$(this).attr('class');
if(cls=='focus'){
alert($(this).index());
}
});
});