How to process NodeList as an Array in javascript _ javascript skills

Source: Internet
Author: User
In Web Front-end programming, we usually use the document. getElementsByTagName method to retrieve a group of dom elements with the same tag. For example:

The Code is as follows:


Var anchors = document. getElementsByTagName ("");
For (I = 0; I <anchors. length; I ++ ){
Var ele = anchors [I]; // obtain an element
// Some code here
}


The code above indicates getting all the link elements in the document, and then traversing to do something.
Maybe you will ask, isn't the dom element obtained in this way an array? You can get the length attribute directly, and obtain the corresponding individual elements based on the index. According to the famous duck theory of Daniel, it walks like a duck (with the length attribute) and calls like a duck (based on the index value), then it is a duck. The conclusion is self-explanatory, right?
If you have a little in-depth understanding of javascript and have the length attribute, can you index the value? Must it be an array? It seems that arguments will do the same thing. Is arguments an array? Although we operate on it as a normal array during actual development, length and for loops are not easy to use, and errors may not occur.
However, it is not an Array, but a NodeList. NodeList is not an array.
What a surprise, right?

1. Why is NodeList not an array?

Verify whether NodeList is an Array. The most direct method may be to try the dedicated push and pop methods of Array:

The Code is as follows:


Var anchors = document. getElementsByTagName ("");
Var newEle = document. createElement ("a"); // create a new a Element
Anchors. push (newEle); // push
Var element = anchors. pop (); // pop


You can test it by yourself. The above code, whether it is the push or pop method, will prompt you that there is no push or pop method. Do you have any questions? Is this the end? This one-sided test made the pig unable to rest comfortably. We can prove in the same way that arguments is not an array, and that NodeList is not an array. See the following code:

The Code is as follows:


Array. prototype. testNodeList = "test nodelist"; // Add a prototype attribute to an Array.
Function funcNodeList (){
Var links = document. getElementsByTagName ("");
Alert (links. testNodeList );
}
Function test (){
Alert (new Array (). testNodeList); // test nodelist
FuncNodeList (); // # ff0000? What the hell is that?
}
Test (); // test it



Through the above analysis, we can be sure that NodeList is not an Array. So how do we operate NodeList according to our collection habits?

2. Operate NodeList like an Array

Since NodeList has length, it is not easy to convert it into an array because it can be a for loop index value? Haha, the most direct idea is this: g

The Code is as follows:


Var arr = new Array ();
Var anchors = document. getElementsByTagName ("")
For (var I = 0; I <anchors. length; I ++ ){
Var ele = anchors [I];
Arr. push (ele); // arr is the array we want
}


Briefly describe it: first create an Array, traverse NodeList, then push each individual element to the Array variable, and finally operate the Array variable, over. Is there any feeling of being humiliated by IQ?
The above is not a joke with you, because the following code is obtained by Lou pig on the Internet, and the two lines of code can be used to convert NodeList to Array:

The Code is as follows:


Var anchors = document. getElementsByTagName ("");
Var arr = Array. prototype. slice. call (anchors); // non-IE browser normal



However, the most unfortunate thing happened: the above Code cannot work normally in the evil IE, and IE will prompt you: The JScript object is missing.
You may not be able to ignore the previous analysis and think there is no need to convert NodeList into an Array. Actually, Lou pig personally believes that type conversion is unwise in any programming language. The most common problems include packing and unpacking in c #, numeric data conversion, and performance problems. But why should Lou pig treat NodeList as an Array? When NodeList is dynamically changed, direct operations on NodeList are likely to mistakenly break into the forbidden zone without knowing it. The following is an example:
(1) html document snippets


Link test


(2) javascript test code

The Code is as follows:


Var anchors = document. getElementsByTagName ("");
For (I = 0; I <anchors. length; I ++ ){
Var ele = document. createElement ("");
Ele. setAttribute ("href", "http://www.cnblogs.com/jeffwongishandsome ");
Ele. appendChild (document. createTextNode ("new link test "));
Document. getElementById ("pAnchor"). appendChild (ele); // p attaches a new link
}


After the file is loaded, execute the above script. Our intention is to append an existing a element to p. However, you can run it. Is the browser crash gone? Lou pig crashes IE directly. FF prompts that the script is busy and whether to stop running. After you click "stop", n a links are generated on the page. In fact, we can boldly analyze the cause: for Loop NodeList (premise: a new element is added to the for loop to change the nodelist length. Thanks to Chen Tong shoes for their superior suggestions), its length will keep changing and rising, and it will be recycled cyclically, and finally it will become an endless loop. The following code is the same as we expected:

The Code is as follows:


Var links = document. getElementsByTagName ("");
Var anchors = null; // Array
Try {
Anchors = Array. prototype. slice. call (links );
}
Catch (e) {// compatible with ie
Anchors = new Array ();
For (var I = 0; I <links. length; I ++ ){
Anchors. push (links [I]);
}
}
For (I = 0; I <anchors. length; I ++) {// array loops are much safer
Var ele = document. createElement ("");
Ele. setAttribute ("href", "http://www.cnblogs.com/jeffwongishandsome ");
Ele. appendChild (document. createTextNode ("new link test "));
Document. getElementById ("pAnchor"). appendChild (ele); // p attaches a new link
}


Then you may ask, isn't the conversion possible? Not so rigid, of course, we can, as long as we are familiar with the coding habits of a little bit of small surgery can be:

The Code is as follows:


Var anchors = document. getElementsByTagName ("");
Var len = anchors. length; // defines a variable.
For (I = 0; I <len; I ++) {// loop the partial variable len
Var ele = document. createElement ("");
Ele. setAttribute ("href", "http://www.cnblogs.com/jeffwongishandsome ");
Ele. appendChild (document. createTextNode ("new link test "));
Document. getElementById ("pAnchor"). appendChild (ele); // p attaches a new link
}


Thank you for reading this article, no matter whether you have any questions or how to choose the actual programming. Looking forward to your guidance.
By Jeff Wong

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.