我不确定我当前的实现是否始终可用:
function isNodeList(nodes) {
var result = Object.prototype.toString.call(nodes);
// modern browser such as IE9 / firefox / chrome etc.
if (result === '[object HTMLCollection]' || result === '[object NodeList]') {
return true;
}
//ie 6/7/8
if (typeof(nodes) != 'object') {
return false;
}
// detect length and item
if (!('length' in nodes) || !('item' in nodes)) {
return false;
}
// use the trick NodeList(index),all browsers support
try {
if (nodes(0) === null || (nodes(0) && nodes(0).tagName)) return true;
}
catch (e) {
return false;
}
return false;
}
常见的情况是 {length:1,item:function(){return [];}}
chrome/safari/opera 中 result 的值为“[object NodeList]”。
在 Firefox 和 IE 9 中,它是“[object HTMLCollection]”。
标准值是多少?
最佳答案
如果节点的类型为NodeList,则以下内容应返回true
NodeList.prototype.isPrototypeOf(nodes)
@DavidSpector,对于HTMLCollection,您可以类似地使用:
HTMLCollection.prototype.isPrototypeOf(collection)
关于javascript - 如何在 JavaScript 中检测 HTMLCollection/NodeList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40457816/