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?
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With