how to check if given variable is a collection of html elements?
For example a type of 开发者_如何转开发data that getElementsByClassName
or getElementsByTagName
produces.
use this code:
var result = document.getElementsByTagName("div");
if (result && result.constructor.name == "NodeList"){
// your code here ;)
}
or this could be more browser safe
var result = document.getElementsByTagName("div");
if (result && getClassName(result) == "htmlcollection"){
// your code here ;)
}
function getClassName(obj){
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
Try this:
function isCollection(input)
{
return input.item != undefined;
}
But beware any other objects with the method item
defined.
精彩评论