Concatenating html object arrays with javascript

user3718546 picture user3718546 · Jun 10, 2014 · Viewed 8.3k times · Source

I'm attempting to merge two arrays made up of html objects. For some reason using .concat() will not work for me.

Here's a simple pen to demonstrate the problem: http://codepen.io/anon/pen/kIeyB

Note: I tried searching for something remotely similar but found nothing that answered my question.

I figure you can do this the ole fashion way using for-loops but I rather not re-invent the wheel.

var x = document.getElementById("hello");
var items = x.getElementsByClassName("one");
//alert(items.length);
var items2 = x.getElementsByClassName("two");
//alert(items2.length);
items = items.concat(items2);
//alert(items.length);

Answer

jfriend00 picture jfriend00 · Jun 10, 2014

items and items2 are nodeList or HTMLCollection objects, not arrays. They do not contain a .concat() method. They have a .length property and support [x] indexing, but they do not have the other array methods.

A common workaround to copy them into an actual array is as follows:

// convert both to arrays so they have the full complement of Array methods
var array1 = Array.prototype.slice.call(x.getElementsByClassName("one"), 0);
var array2 = Array.prototype.slice.call(x.getElementsByClassName("two"), 0);