In Web front-end programming, we usually take a document.getelementsbytagname approach to get a set of DOM elements of the same label, such as:
var list = document.getElementsByTagName ("li");
for (i = 0; i < list.length i++) {
var lis = list[i];//Fetch an element
//more code
First, this group of DOM elements obtained by this method is not an array, but rather a nodelist,nodelist is not an array.
We can get its length property directly, and we can also take the corresponding individual elements according to the index, is not an array? If you've had a bit of a deep understanding of JavaScript, have the length attribute, you can index the value, it must be an array, as if arguments would do it, arguments is an array. Of course not.
1, NodeList Why is not an array.
To verify that nodelist is not an array, the most straightforward approach might be to try the array-specific push and pop methods:
var list = document.getElementsByTagName ("li");
var a = document.createelement ("a");//New A element
List.push (a);//push
var element= list.pop ();//pop
By testing, the above code, whether it's a push or a pop method, prompts you without a push or pop method. Of course this test is a bit one-sided. We can prove that the nodelist is not an array, as it is to prove that arguments is not an array. That is to modify its prototype, to test. Look at the code below:
Array.prototype.testNodeList = "Test NodeList"; Array Add prototype property
function NodeList () {
var list = document.getelementsbytagname ("li");
alert (list.testnodelist);
}
function test () {
alert (new Array (). testnodelist);//test nodelist
nodelist ();//undefined
}
Test (); Test
Through the above analysis, we can be sure that nodelist is not an array. So how do we operate the nodelist according to the custom of our operation set?
2, like Operation array Operation NodeList
Since nodelist has length, you can take values for the loop index, and converting the array is not easy. The most direct idea is this: start with a new array, traverse the nodelist, then push each individual element into the array variable, and finally manipulate the array variable.
var arr = [];
var list = document.getElementsByTagName ("li");
for (var i = 0; i < list.length i++) {
var li = list[i];
Arr.push (LI); Arr is the array we want.