3

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Joey
  • 10,504
  • 16
  • 39
  • 54
  • Array structures must be identical to use concat. These element selectors produce results that are not. These are not simple lists - they're objects. – Diodeus - James MacFarlane Mar 01 '12 at 19:32
  • In addition see this: http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript – Richard A Mar 01 '12 at 19:37
  • Also see: [http://stackoverflow.com/questions/914783/javascript-nodelist](http://stackoverflow.com/questions/914783/javascript-nodelist) – wave Mar 01 '12 at 19:40
  • You could: `var elems = document.getElementById( div_id ).querySelectorAll( 'input, textarea, select' );` – Šime Vidas Mar 01 '12 at 19:47

2 Answers2

4

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);
nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
1

Those methods don't return an Array. Instead it's a NodeList or perhaps an HTMLCollection. (See the note under Syntax.)

You might loop over each nodelist and form an array of them 'by hand'.

pc1oad1etter
  • 8,549
  • 10
  • 49
  • 64