Javascript: operate nodelist like an array

Source: Internet
Author: User

In front-end web programming, we usually use the document. getelementsbytagname method to retrieve a group of DOM elements with the same tag, such:

 
VaR anchors = Document. getelementsbytagname ("");
For (I = 0; I <anchors. length; I ++ ){
VaR ele = anchors [I]; // obtain an element // some code here
}

The aboveCodeObtains all the link elements in the document, and then traverses and performs some operations.
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:

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:

 
Array. Prototype. testnodelist = "test nodelist"; // Add a prototype attribute to an array.
Function funcnodelist () {var links = Document. getelementsbytagname ("A"); alert (links. testnodelist );}
Function Test () {alert (new array (). testnodelist); // test nodelistfuncnodelist (); // # 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:

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:

 
VaR anchors = Document. getelementsbytagname ("");
VaR arr = array. Prototype. Slice. Call (anchors); // non-IE browser normal

The slice method can be used to convert array objects such as arguments and nodelist into arrays. Lou pig Note] However, the most unfortunate thing happened: the above Code cannot work normally under the evil IE, 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 also thinks that no matter whatProgramming LanguageType conversion is unwise. 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

< Div ID = "Divanchor" >
< A Href = "Http://www.cnblogs.com/jeffwongishandsome" > LINK TEST </ A >
</ Div >

(2) JavaScript test code

 
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 ("divanchor"). appendchild (Ele); // Add a new link to the div.
}

After the file is loaded, execute the above script. Our intention is to add an existing a element to the DIV and then add it to it. 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:

 
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 ("divanchor"). appendchild (Ele); // Add a new link to the div.
}

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:

 
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 ("divanchor"). appendchild (Ele); // Add a new link to the div.
}

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.

Related Article

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.