I would like to determine if a variable is a an array of DOM elements NodeList or a single DOM element. I tried Array.isArray(x) but it returns false when x = document.getElementsByClassName("test") because it is a NodeList not an array.
Is there a an alternative way to do this?
The solution I came up with was to test if typeof x.attributes == "undefined", presuming that all DOM elements will have an attributes property. Is there anything wrong with this?
sample:
var x = document.getElementsByClassName("test");
var y = x[0];
console.log(Array.isArray(x));                   // returns false
console.log(typeof x.attributes == "undefined"); // returns true
console.log(Array.isArray(y));                   // returns false
console.log(typeof y.attributes == "undefined"); // returns false
sample html:
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>