admin管理员组文章数量:1336632
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());
}
});
});
本文标签: javascriptHow to find the position for an element in a li with jquery or vanilla jsStack Overflow
版权声明:本文标题:javascript - How to find the position for an element in a li with jquery or vanilla js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742414712a2470492.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论