Search code examples
javascriptarrayshtml-object

Concatenating html object arrays with javascript


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);

Solution

  • 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);