Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 395
user3718546 Avatar asked Jun 10 '14 05:06

user3718546


People also ask

How do you concatenate arrays in JavaScript?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.

How do you concatenate an object to an array?

JavaScript concat() Method : Array ObjectThe concat() method is used to join two or more arrays. Concat does not alter the original arrays, it returns a copy of the same elements combined from the original arrays. arrayname1, arrayname2, ..., arraynameN : Arrays to be joined to an array.

Can we concat two arrays in JavaScript?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do you merge an array of objects into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.


1 Answers

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);
like image 138
jfriend00 Avatar answered Oct 29 '22 21:10

jfriend00