getElementsByTagName (and similar methods such as getElementsByName , getElementsByClassName , etc.) returns a NodeList (or an HTMLCollection , depending on the browser, apparently, see also the Difference between HTMLCollection, NodeLists and object arrays ).
Even if it is an object with an array , i.e. it has numeric properties and the .length property, you cannot add new elements to it.
To change a NodeList , you need to convert it to a regular array. This can be easily achieved using the .slice array .slice and at the same time, you can combine both lists with .concat :
bar = Array.prototype.slice.call(bar).concat(Array.prototype.slice(foo));
This works because most of the array's own methods are defined in such a way that the argument should not be actually an array, but an array.
Noticeable differences between a NodeList and the final array:
- The array no longer lives, i.e. the collection does not update automatically when new DOM nodes are added.
- Elements in a finite (concatenated) array will not necessarily be in document order.
source share