I\'m not sure my current implementation is available all the time:
function isNodeList(nodes) {
var result = Object.prototype.toString.call(nodes);
/
The following should return true, if nodes is of type NodeList
NodeList.prototype.isPrototypeOf(nodes)
@DavidSpector, for HTMLCollection you can similarly use :
HTMLCollection.prototype.isPrototypeOf(collection)
This answer is probably really really late, but....
if (nodes == '[object NodeList]') {
// It's a nodeList
}
Here is how to test if an object is a NodeList in modern browsers:
if (nodes instanceof NodeList) {
// It's a NodeList object
}
Check if variable is an HTMLcollection or a dom element
var foo = document.getElementById('mydiv');
var foo2 = document.getElementsByClassName('divCollection');
console.log(foo instanceof HTMLElement);
console.log(foo instanceof HTMLCollection);
I created a benchmark of all answers here to see, what is the best approve in speed. Turns out NodeList.prototype.isPrototypeOf(nodes)
is by far the fastest. But in a normal use-case nodes instanceof NodeList
would be fine too.
I personally would just not pick the isNodeList
function, because its slow, custom and too much overhead.
I would structure the code differently:
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));
}
Notes:
"item"
is not mandatorily in a nodeListhasOwnProperty()
instead of in
nodeType
instead of tagName
, as text nodes or comments do not have a name&&
chain if you see fit