How To Detect Htmlcollection/nodelist In Javascript?
I'm not sure my current implementation is available all the time: function isNodeList(nodes) { var result = Object.prototype.toString.call(nodes); // modern browser such as
Solution 1:
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)
Solution 2:
I would structure the code differently:
functionisNodeList(nodes) {
var stringRepr = Object.prototype.toString.call(nodes);
returntypeof nodes === 'object' &&
/^\[object (HTMLCollection|NodeList|Object)\]$/.test(stringRepr) &&
(typeof nodes.length === 'number') &&
(nodes.length === 0 || (typeof nodes[0] === "object" && nodes[0].nodeType > 0));
}
Notes:
- less return paths make easier-to-read code
- stick with one type of logic, if possible (i.e. use less negated checks)
"item"
is not mandatorily in a nodeList- use
hasOwnProperty()
instead ofin
- use square brackets to index into the list
- I don't think a try/catch is really necessary, but that might be wrong - you decide
- check for
nodeType
instead oftagName
, as text nodes or comments do not have a name - add more checks to the
&&
chain if you see fit
Solution 3:
script:
Element.prototype.isNodeList = function() {returnfalse;}
NodeList.prototype.isNodeList = HTMLCollection.prototype.isNodeList = function(){returntrue;}
use like this:
var d; // HTMLCollection|NodeList|Elementif(d.isNodeList()){
/*
it is HTMLCollection or NodeList
write your code here
*/
}else{
/*
it is not HTMLCollection and NodeList
write your code here
*/
}
Solution 4:
Here is how to test if an object is a NodeList in modern browsers:
if (nodes instanceof NodeList) {
// It's a NodeList object
}
Solution 5:
Check if variable is an HTMLcollection or a dom element
var foo = document.getElementById('mydiv');
var foo2 = document.getElementsByClassName('divCollection');
console.log(foo instanceofHTMLElement);
console.log(foo instanceofHTMLCollection);
Post a Comment for "How To Detect Htmlcollection/nodelist In Javascript?"