简体   繁体   中英

How does JavaScript store DOM elements in variables?

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, ie 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, ie 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.

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.

eg,

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

foo becomes the function. So you wouldn't be able to add foo to bar because that doesn't make sense. It would be like trying to do:

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

You could have multiple elements in a single array. I'd find that to be the simplest way to reach your solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM