Search code examples
javascriptarraysconcatenationgetelementsbytagname

Combining arrays returned by getElementsByWhatever


I am trying to get all the form elements within a specific div, and combine them into a single array using the array concat() method:

var div_id = 'some_div_id'; // in real life this is passed as a function parameter

var child_inputs = document.getElementById(div_id).getElementsByTagName('input');
var child_textareas = document.getElementById(div_id).getElementsByTagName('textarea');
var child_selects = document.getElementById(div_id).getElementsByTagName('select');

var field_elements = child_inputs.concat(child_textareas, child_selects); // this doesnt work?

However the script fails at the last line I'm not sure why. I can't use .childNodes because the div_id being passed is not the direct parent.


Solution

  • getElementsByTagName returns a NodeList not an array, so you can't use concat.

    If you want to "transform" the nodeList into an array you could call slice from the Array protype chain:

    var div_id = 'some_div_id',
        divIdElement = document.getElementById(div_id); //cache the element
    
    var getArrayFromTag = function(tagname) {
         //get the NodeList and transform it into an array
         return Array.prototype.slice.call(divIdElement.getElementsByTagName(tagname));
    }
    
    //Get the arrays
    var child_inputs = getArrayFromTag('input');
    var child_textareas = getArrayFromTag ('textarea');
    var child_selects = getArrayFromTag ('select');
    
    //use concat
    var field_elements = child_inputs.concat(child_textareas, child_selects);