javascript - 如何在 JavaScript 中检测 HTMLCollection/NodeList?

标签 javascript

我不确定我当前的实现是否始终可用:

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/

相关文章:

javascript - 无法将参数传递给 chrome.declarativeContent.SetIcon

javascript - mongoDB:删除对象数组中的空对象

javascript - 定时 promise 队列/节流

javascript - Firebase 是否缓存数据?

javascript - 如何编写验证函数

javascript - 在 iframe 中分享 Google+

javascript - 带有 Bootstrap 的 SyntaxHighlighter 边距错误?

javascript - 如何仅设置数值输入字段的边框颜色?

javascript - 一种如何在Angular中设置大型动态文本字符串的样式?

javascript - google maps fusiontable 图层正在加载或完成加载时触发事件?