How does JavaScript store DOM elements in variables?

12,937

Solution 1

getElementsByTagName (and similar methods such as getElementsByName, getElementsByClassName, etc) returns a NodeList (or HTMLCollection, depending on the browser apparently, see also Difference between HTMLCollection, NodeLists, and arrays of objects).

Even though it is an array-like object, i.e. it has numeric properties and a .length property, you cannot add new elements to it.

In order to modify the NodeList, you have to convert it to a regular array. This can easily be achieved with the array method .slice and at the same time you can merge both lists with .concat:

bar = Array.prototype.slice.call(bar).concat(Array.prototype.slice(foo));

This works because most native array methods are defined in such a way that the argument does not have to be an actually array, but an array-like object.

The noteworthy differences between a NodeList and the final array are:

  • The array is not live anymore, i.e. the collection is not automatically updated when new DOM nodes are added.
  • The elements in the final (merged) array won't necessarily be in document order.

Solution 2

bar =+ foo;

this works only for string concatenation and it would be bar+= foo

but both bar and foo here are DOM objects. so if you want to add elements of the same type u can create an array.

e.g.,

var myArray =[]
myArray.push(foo);
myArray.push(bar);
Share:
12,937
Samuel Lopez
Author by

Samuel Lopez

Relaxed and chilled person who loves music (who does not?), pretty much all types of games (loves racing simulation a lot), and any type of interesting information.

Updated on June 23, 2022

Comments

  • Samuel Lopez
    Samuel Lopez almost 2 years

    What I mean is how does JavaScript store DOM elements when you do something like:

    var foo = document.getElementsByTagName('p');
    

    what does foo become? an array of objects? and how can I add more elements to that variable, for example:

    var bar = document.form[0].getElementsByTagName('input'); // 5 elements
    var foo = document.form[1].getElementsByTagName('input'); // 4 elements
    
    bar =+ foo;
    
    for (i=0;i<bar.length;i++){
    console.log(bar.value); // 9 logged values
    }
    

    Is it possible to add more elements of the same type to a variable that already has elements in it? Do I have to loop trough all elements in the variable I want to add and "push" them in the variable I want all the data in?