How to Use nodelist as an array in Javascript

Source: Internet
Author: User

For example: CopyCode 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:Copy codeThe 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:Copy codeThe Code is as follows: array. Prototype. testnodelist = "test nodelist"; // Add the prototype attribute to the 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: GCopy codeThe 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:Copy codeThe 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 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

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

after the file is loaded, run the script above. 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: copy Code the code is as follows: var links = document. getelementsbytagname ("A");
var anchors = NULL; // array
try {
anchors = array. prototype. slice. call (LINKS);
}< br> catch (e) {// compatible with IE
anchors = new array ();
for (VAR I = 0; I anchors. push (Links [I]);
}< BR >}< br> for (I = 0; I var ele = document. createelement ("A");
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 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:Copy codeThe 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 ("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.
By Jeff Wong

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.