簡體   English   中英

如何在JavaScript中檢測HTMLCollection / NodeList?

[英]How to detect HTMLCollection/NodeList in 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中的結果值是'[object NodeList]'。
在firefox和IE 9中,它是'[object HTMLCollection]'。

哪個是標准值?

, if nodes is of type NodeList 如果節點類型為NodeList ,則以下內容應返回

NodeList.prototype.isPrototypeOf(nodes)

@DavidSpector,對於HTMLCollection,您可以類似地使用:

HTMLCollection.prototype.isPrototypeOf(collection)

我會以不同的方式構造代碼:

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));
}

筆記:

  • 較少的返回路徑使代碼更容易閱讀
  • 如果可能的話,堅持使用一種邏輯(即使用較少的否定支票)
  • "item"不是強制在nodeList中
  • 使用hasOwnProperty()而不是in
  • 使用方括號來索引列表
  • 我不認為嘗試/捕獲是真的必要,但這可能是錯的 - 你決定
  • 檢查nodeType而不是tagName ,因為文本節點或注釋沒有名稱
  • 如果您認為合適,請在&&鏈中添加更多檢查

腳本

Element.prototype.isNodeList = function() {return false;}
NodeList.prototype.isNodeList = HTMLCollection.prototype.isNodeList = function(){return true;}

使用這樣

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
  */
}

以下是如何在現代瀏覽器中測試對象是否為NodeList:

if (nodes instanceof NodeList) {
  // It's a NodeList object
}

檢查變量是HTMLcollection還是dom元素

  var foo = document.getElementById('mydiv');
  var foo2 = document.getElementsByClassName('divCollection');
  console.log(foo instanceof HTMLElement);
  console.log(foo instanceof HTMLCollection);

這個答案可能真的很晚,但....

if (nodes == '[object NodeList]') {
  // It's a nodeList
}

我在這里創建了所有答案的基准,看看速度最佳的批准是什么。 結果是NodeList.prototype.isPrototypeOf(nodes)是迄今為止最快的。 但在正常的用例nodes instanceof NodeList也可以。

我個人不會選擇isNodeList函數,因為它的速度慢,自定義和開銷太大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM