rsk82
rsk82

Reputation: 29397

how to check if given variable is a collection of html elements?

For example a type of data that getElementsByClassName or getElementsByTagName produces.

Upvotes: 1

Views: 96

Answers (2)

Fareed Alnamrouti
Fareed Alnamrouti

Reputation: 32174

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

Upvotes: 1

Daniel O'Hara
Daniel O'Hara

Reputation: 13438

Try this:

function isCollection(input)
{
    return input.item != undefined;
}

But beware any other objects with the method item defined.

Upvotes: 0

Related Questions