0
var b = document.getElementsByName("button");
var l = document.getElementsByName("link");

Which is the best way to add the content of these two arrays into one? I don't want to use for loop

Srikanth Kshatriy
  • 444
  • 1
  • 4
  • 10
  • 2
    The same - http://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript? – Ilia Frenkel Apr 13 '12 at 05:57
  • possible duplicate of [JavaScript NodeList](http://stackoverflow.com/questions/914783/javascript-nodelist) – bfavaretto Apr 13 '12 at 05:58
  • 3
    Those are not arrays, they're `NodeList` objects. See the [accepted answer](http://stackoverflow.com/a/914995/825789) to the question I linked as a dupe (that solution does not involve a for loop) – bfavaretto Apr 13 '12 at 06:01
  • Define your criteria for "best". – RobG Apr 13 '12 at 06:14

1 Answers1

3

You can use Array.prototype.slice.call() to turn the nodeLists into real arrays and then use array operations on them to combine them

var b = document.getElementsByName("button");
var l = document.getElementsByName("link");
// make both nodeLists into real arrays
var copyB = Array.prototype.slice.call(b, 0);
var copyL = Array.prototype.slice.call(l, 0);
var combined = copyB.concat(copyL);

Working demo: http://jsfiddle.net/jfriend00/vZ5tb/

Or, a little briefer version:

var copyB = Array.prototype.slice.call(document.getElementsByName("button"), 0);
var copyL = Array.prototype.slice.call(document.getElementsByName("link"), 0);
var combined = copyB.concat(copyL);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Why answering this instead of closing the question as a dupe? Question and answer are nearly identical to the ones I linked to. – bfavaretto Apr 13 '12 at 14:34