[英]How to find the position for an element in a li with jquery or vanilla js
Lets imagine I have the following HTML code.假设我有以下 HTML 代码。
I need to find the position within the LI elements for the LI which has the class focus applied.我需要在应用了类焦点的 LI 元素中找到位置。
In this example the result should be 2 (if at 0 index).在此示例中,结果应为 2(如果索引为 0)。 Any idea how to do it?
知道怎么做吗?
<ul class="mylist">
<li>Milk</li>
<li>Tea</li>
<li class="focus">Coffee</li>
</ul>
While you've already accepted an answer to your question, I thought I'd put together a simple index()
method for HTMLElement
s:虽然您已经接受了问题的答案,但我想我应该为
HTMLElement
s 组合一个简单的index()
方法:
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:参考:
the expanded version (jquery) would be扩展版本(jquery)将是
$(document).ready(function(){
$('li').each(function(){
var cls=$(this).attr('class');
if(cls=='focus'){
alert($(this).index());
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.