How does JavaScript store DOM elements in variables?

I mean, how JavaScript stores DOM elements when you do something like:

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

what does foo do? an array of objects? and how can I add additional elements to this 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 several elements of the same type to a variable in which there are already elements? Do I need to iterate over all the elements in the variable that I want to add and โ€œclickโ€ them in the variable in which I want all the data?

+4
source share
3 answers

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.
+8
source

bar = + foo;

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

but both bars and foo here are DOM objects. therefore, if you want to add elements of the same type, you can create an array.

eg.

 var myArray =[] myArray.push(foo); myArray.push(bar); 
+1
source

foo becomes a function. Thus, you cannot add foo to bar, because it does not make sense. This would be like trying:

 document.form[0].getElementsByName('input') document.form[1].getElementsByName('input'); 

You can have multiple elements in one array. I think this is the easiest way to reach your decision.

-4
source

Source: https://habr.com/ru/post/1487160/


All Articles