首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JavaScript中检测HTMLCollection/NodeList?

如何在JavaScript中检测HTMLCollection/NodeList?
EN

Stack Overflow用户
提问于 2011-08-30 10:48:52
回答 6查看 26.1K关注 0票数 30

我不确定我当前的实现是否一直可用:

代码语言: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和IE9中,它是'object HTMLCollection‘。

哪个是标准值?

EN

回答 6

Stack Overflow用户

发布于 2011-08-30 11:22:35

我会以不同的方式构建代码:

代码语言:javascript
运行
复制
function isNodeList(nodes) {
    var stringRepr = Object.prototype.toString.call(nodes);

    return typeof nodes === 'object' &&
        /^\[object (HTMLCollection|NodeList|Object)\]$/.test(stringRepr) &&
        (typeof nodes.length === 'number') &&
        (nodes.length === 0 || (typeof nodes[0] === "object" && nodes[0].nodeType > 0));
}

备注:

使用较少的返回路径使代码更易于阅读,并坚持一种类型的逻辑,如果可能的话(即,在nodeList

  • 中不强制使用较少的求反路径使用hasOwnProperty()而不是checks)

  • "item"方括号来索引列表

  • 我不认为尝试/捕获真的是必要的,但这可能是错误的-您决定检查<代码>H216H117,而不是检查<代码>D19,由于文本节点或注释没有名称,因此如果您看到

  • ,请向&&链添加更多检查
票数 24
EN

Stack Overflow用户

发布于 2014-04-23 23:23:22

脚本

代码语言:javascript
运行
复制
Element.prototype.isNodeList = function() {return false;}
NodeList.prototype.isNodeList = HTMLCollection.prototype.isNodeList = function(){return true;}

像这样使用

代码语言:javascript
运行
复制
var d; // HTMLCollection|NodeList|Element
if(d.isNodeList()){
  /*
    it is HTMLCollection or NodeList
    write your code here
  */
}else{
  /*
    it is not HTMLCollection and NodeList
    write your code here
  */
}
票数 13
EN

Stack Overflow用户

发布于 2016-10-11 03:56:45

下面是如何在现代浏览器中测试对象是否为NodeList:

代码语言:javascript
运行
复制
if (nodes instanceof NodeList) {
  // It's a NodeList object
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7238177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档