JavaScript - DOM object check array & isArray polyfill
Table of Contents
#
JavaScript - DOM object check array & isArray polyfill
One day my colleague find a question.
ECMA script isArray
is not work when object is DOM element
Array.isArray(document.querySelectorAll('div'));
// false
And polyfill for old browser
Object.prototype.toString.call(arg) === '[object Array]';
Still fail
Object.prototype.toString.call(document.getElementsByClassName('product-img'));
// [object HTMLCollection]
Object.prototype.toString.call(document.querySelectorAll('div'));
// [object NodeList]
So i try to make a polyfill
Array.isArray = function(arg) {
var type = Object.prototype.toString.call(arg);
if (type === '[object Array]' ||
type === '[object HTMLCollection]' ||
type === '[object NodeList]') {
return true;
}
return false;
};