Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JavaScript store DOM elements in variables?

Tags:

javascript

dom

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?

like image 409
Samuel Lopez Avatar asked Jun 19 '13 21:06

Samuel Lopez


2 Answers

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.
like image 176
Felix Kling Avatar answered Nov 02 '22 09:11

Felix Kling


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);
like image 24
Gokul Kav Avatar answered Nov 02 '22 07:11

Gokul Kav