Methods for processing nodelist as array arrays in JavaScript

Source: Internet
Author: User

Transferred from: http://www.jb51.net/article/24182.htm

var anchors = document.getElementsByTagName ("a");  for (i = 0; i < anchors.length; i++) {var ele=anchors[i]; // take an element // some code here

The above code means getting all the link elements in the document and then traversing through to do something.
Perhaps you would ask, is this a set of DOM elements obtained by this method not just an array? You see, you can directly get its length property, you can also take the corresponding individual elements according to the index, according to the famous Duck theory of Daniel, it walks like a duck (with the length attribute), like a duck bark (according to the index value), then it is a duck. Is the conclusion self-evident?
If you have a little bit of JavaScript in-depth understanding, there is the length property, you can index the value, must be an array, it seems that arguments will be such a hand, arguments is an array? While actually developing it, we use it as an ordinary array to manipulate the exhilaration of length and for loops, and it is not always an error.
However, it is really not an array, but rather a nodelist. NodeList is not an array.
What a surprise,right?

1. Why is nodelist not an array?

The most straightforward way to verify that nodelist is not an array is to try array-specific push and pop Dafa:

var anchors = document.getElementsByTagName ("a"); var newele = document.createelement ("a"); // create a new A element Anchors.push (Newele); // Push var element= Anchors.pop (); // Pop

You can test it yourself, the above code, whether it is a push or pop method, without exception will prompt you no push or pop method. Do you have any questions? Is this the end of it? This one-sided test has made the building pigs unable to rest comfortably. We can just as well prove that arguments is not an array, and that the same method proves that nodelist is not an array. Let's look at the following code:

 Array.prototype.testNodeList = "Test NodeList"; //  array add prototype properties  function   Funcnodelist () { var  links = document.getElementsByTagName ("A"  function   Test () {alert ( new  Array (). testnodelist ); // test nodelist  funcnodelist (); //  #ff0000? What's the hell is?  }test ();  //  test  

With the above analysis, we can be sure that nodelist is not an array. So how do we operate the nodelist according to the habits of our collection?

2. Operate nodelist like Operation Array

Since nodelist has length, can be used for loop index value, conversion of the array is not easy? Haha, the most direct idea is this:

var New Array (); var anchors = document.getElementsByTagName ("a") for (var i = 0; i < Anchors.length; i++) {var ele =//arr is the array we want

Explain briefly: first new array, Traverse nodelist, then push each individual element into the array variable, and finally manipulate the array variable, over. Is there a feeling of an IQ insult?
This is not to joke with you, because the following is the floor of the pig on the internet Google to, two lines of code can convert nodelist into an array to use:

var anchors = document.getElementsByTagName ("a"); var //

However, the most regrettable thing happened: The above code in the evil IE does not work properly, IE will give you a hint: the lack of JScript objects.
You may be dismissive of a large analysis above, and think that it is not necessary to convert nodelist into an array. In fact, the individual of Lou Pig also thinks, regardless of in which programming language, the type conversion is very unwise behavior. The most common examples are boxed and unboxing in C #, numeric data conversions, performance problems, and accidents. But why does the building pig have to treat nodelist as an array alone? Because of the dynamic change of the nodelist, the direct operation of NodeList is likely to accidentally break into the forbidden area and unaware. Here's an example:
(1), HTML document fragment

<id= "Divanchor"><href= "http:/ /www.cnblogs.com/jeffwongishandsome/">link Test</a> </ Div >

(2), JavaScript test code

var anchors = document.getElementsByTagName ("a");  for (i = 0; i < anchors.length; i++) {var ele= document.createelement ("a"); Ele.setattribute (" href "," http://www.cnblogs.com/jeffwongishandsome/"); Ele.appendchild (document.createTextNode (" New link Test "));d Ocument.getelementbyid (//div append a new link

After the document has finished loading, execute the above script. Our intention is to add an a element to the DIV, after an already existing a element. However, you can run it, the browser crash off it? Lou Pig here ie directly hanging off, FF prompt script is busy, whether to stop the script to run, click Stop, the page has generated more than n a link. In fact, we can boldly analyze the reason: For Loop NodeList (premise: A new element is added inside the for loop to make the NodeList length change.) Thanks to Chen Dong shoes, the length of the shoe is constantly changing, the cycle is recycled, and finally it becomes a dead loop. And the following code, as we expected the effect is the same:

varLinks = document.getElementsByTagName ("a");varAnchors =NULL;//ArrayTry{Anchors=Array.prototype.slice.call (links);}Catch(e) {//compatible with IEAnchors =NewArray (); for(vari = 0; i < links.length; i++) {Anchors.push (links[i]);}} for(i = 0; i < anchors.length; i++) {//array loops are much safer.varEle = Document.createelement ("a"); Ele.setattribute ("href", "http://www.cnblogs.com/jeffwongishandsome/"); Ele.appendchild (document.createTextNode ("New link Test"));d Ocument.getelementbyid ("Divanchor"). AppendChild (Ele);//Div Append a new link}

Well, you might ask, wouldn't it be okay to convert? Not so rigid, of course, as long as we are familiar with the coding habits of a little bit small surgery can be:

var anchors = document.getElementsByTagName ("a"); var // Define a variable  for // Loop The local variable len var ele = document.createelement ("a"); Ele.setattribute ("href", "http://www.cnblogs.com/ jeffwongishandsome/"); Ele.appendchild (document.createTextNode (" new link Test "); document.getElementById (//div append a new link

Transferred from: http://www.jb51.net/article/24182.htm

Methods for processing nodelist as array arrays in JavaScript

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.