[英]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
}
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.