Javascript 如何在javascript中获取元素的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3779986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the index of the element in javascript?
提问by Tom Brito
The NodeList don't have a indexOf(element) method? So, how can I get the element index?
NodeList 没有 indexOf(element) 方法?那么,如何获取元素索引呢?
采纳答案by Martijn
By iterating over the elements, and checking if it matches.
通过迭代元素,并检查它是否匹配。
Generic code that finds the index of the element within it's parents childNodes
collection.
在其父childNodes
集合中查找元素索引的通用代码。
function index(el) {
var children = el.parentNode.childNodes,
i = 0;
for (; i < children.length; i++) {
if (children[i] == el) {
return i;
}
}
return -1;
}
Usage:
用法:
// should return 4
var idx = index(document.body.childNodes[4]);
EDIT: I can't delete an accepted answer, but @kennebec's answer below is much better, which I'll quote verbatim:
编辑:我无法删除已接受的答案,但下面@kennebec 的答案要好得多,我将逐字引用:
You can use
Array.prototype.indexOf.call()
like thislet nodes = document.getElementsByTagName('*'); Array.prototype.indexOf.call(nodes, document.body);
您可以使用
Array.prototype.indexOf.call()
这样的let nodes = document.getElementsByTagName('*'); Array.prototype.indexOf.call(nodes, document.body);
回答by kennebec
You can use Array.prototype.indexOf.call()
like this
您可以使用Array.prototype.indexOf.call()
这样的
let nodes = document.getElementsByTagName('*');
Array.prototype.indexOf.call(nodes, document.body);
回答by Golmote Kinoko
The NodeList objet is an Array-like object. So it's possible to "convert" it into an Array using Array.prototype.slice.call()
NodeList 对象是一个类似数组的对象。因此可以使用“转换”为数组Array.prototype.slice.call()
var arr = Array.prototype.slice.call(yourNodeListObject); // Now it's an Array.
arr.indexOf(element); // The index of your element :)
On browsers that support ES6 you can also do this with Array.from()
在支持 ES6 的浏览器上,您也可以使用 Array.from()
const arr = Array.from(yourNodeListObject);
or using the spread operator ...
或使用扩展运算符...
const arr = [...yourNodeListObject];
回答by Павел П
Just add one line in your script:
只需在脚本中添加一行:
NodeList.prototype.indexOf = Array.prototype.indexOf; // for IE11
Then use indexOfas usual:
然后像往常一样使用indexOf:
var index = NodeList.indexOf(NodeElement);