I am trying to flatten a multidimensional array into a one dimensional array using a recursive function.
My single dimension array elements is returning undefined
JS Bin with my example, here.
HTML:
<span class="one"></span> <span class="one"></span> <span class="two"></span> JS:
// elements collection var elementsCollection = []; var elements = []; /* toSingle * convert mutlidimensional array to one dimensional array (i.e. flatten) * * @param ec - array */ function toSingle (ec) { for (var i = 0; i < ec.length; i++) { if (ec[i].length) { toSingle(ec[i]) } else { elements.push(ec[i]); } } } // get elements by their HTML class name var buttons = [ 'one', 'two' ]; // collect elements from class names for (var i = 0; i < buttons.length; i++) { elementsCollection.push(document.getElementsByClassName(buttons[i])); } // convert multiDimensional array to one dimensional elements = toSingle(elementsCollection); // log console.log(elements); // undefined
querySelectorAll();to receive a single object. See my answer below.