Home Web Front-end JS Tutorial How to handle NodeList as Array array in javascript_javascript tips

How to handle NodeList as Array array in javascript_javascript tips

May 16, 2016 pm 06:23 PM
array array

For example:

Copy code The code is as follows:

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

The above code means to get all the link elements in the document, and then traverse to do something.
Maybe you will ask, isn’t the group of DOM elements obtained through this method an array? You see, you can directly get its length attribute, and you can also get the corresponding individual element according to the index. According to Daniel's famous duck theory, it walks like a duck (has the length attribute) and quacks like a duck (according to the index value), then it is a duck. The conclusion is self-evident, right?
If you already have a little in-depth understanding of javascript, there is a length attribute that can be indexed to get a value. Does it have to be an array? It seems that arguments can do this, right? Are arguments an array? Although in actual development, we operate it as an ordinary array, length and for loops are very easy to use, and there is no need for errors.
However, it is really not an array (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. Perhaps the most direct way is to try Array’s proprietary push and pop methods:
Copy code The code is as follows:

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, whether the above code is push or pop method, without exception, you will be prompted that there is no push or pop method. Still have questions? Is this the end? This kind of one-sided test makes Louzhu unable to sit back and relax. We can use the same method to prove that NodeList is not an array just like we proved that arguments is not an array. Look at the code below:
Copy code The code is as follows:

Array.prototype.testNodeList = "test nodelist"; //Add prototype attribute to array
function funcNodeList() {
var links = document.getElementsByTagName("a");
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 (Array). So how to operate NodeList according to our habit of operating collections?

2. Operate NodeList like Array

Since NodeList has length, it can be indexed by for loop to obtain the value. Isn’t it easy to convert it into an array? Haha, the most direct idea is this: g
Copy the code The code is as follows:

var arr = new Array();
var anchors = document.getElementsByTagName("a")
for (var i = 0; i < anchors.length; i ) {
var ele = anchors[i ];
arr.push(ele); //arr is the array we want
}

Let me explain it clearly: first create an Array, traverse the NodeList, and then add each Push a single element into the array variable, and finally operate on the array variable, over. Do you feel like your intelligence has been insulted?
The above is not a joke to you, because the following is what Lou Zhu found on Google on the Internet. Two lines of code can convert NodeList into Array for use:
Copy Code The code is as follows:

var anchors = document.getElementsByTagName("a");
var arr = Array.prototype.slice.call(anchors) ; //Normal browsers other than IE


However, the most regrettable thing happened: the above code cannot work properly under the evil IE, and IE will give you a prompt: JScript object is missing.
You may be dismissive of the above analysis and think that there is no need to convert NodeList into Array for operation. In fact, Lou Zhu personally believes that type conversion is a very unwise behavior no matter what programming language it is in. The most common ones are boxing and unboxing in C#, and numerical data conversion, which have performance problems and can trigger mine accidents if you are not careful. But why does Lou Zhu treat NodeList as an Array alone? Because when dynamically changing the NodeList, directly operating the NodeList is likely to accidentally enter the restricted area without realizing it. Here is an example:
(1), html document fragment


(2), javascript test code

Copy code The code is as follows:

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"));
document.getElementById("divAnchor").appendChild(ele); // div appends a new link
}

in After the document is loaded, execute the above script. Our original intention is to append an a element after the existing a element within the div. However, you can run it and the browser will crash, right? Louzhu here IE hangs directly, FF prompts the script is busy, whether to stop the script running, after clicking stop, n number of a links have been generated in the page. In fact, we can boldly analyze the reason: for loop NodeList (premise: new elements are added inside the for loop, which changes the length of the nodelist. Thanks to Chen Tongxie for his suggestion), its length will continue to change and rise, and the loop will loop again and again. , and finally became an endless loop. Using the following code, the effect is the same as what we expected:
Copy the code The code is as follows:

var links = document.getElementsByTagName("a");
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 ("a");
ele.setAttribute("href", "http://www.cnblogs.com/jeffwongishandsome/");
ele.appendChild(document.createTextNode("new link test") ; It’s not that rigid, of course it’s possible, just do a little bit of surgery on our familiar coding habits:



Copy code
The code is as follows: var anchors = document.getElementsByTagName("a"); var len = anchors.length; //Define a variable for (i = 0; i < len; i ) { //Loop over 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("divAnchor").appendChild(ele); // div appends a new Link
}


At this point, no matter whether you have any questions or not, I would like to thank you for reading. Looking forward to advice.
Written by: Jeff Wong
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

How to sort values ​​in an array by size in PHP How to sort values ​​in an array by size in PHP Mar 22, 2024 pm 05:24 PM

PHP is a commonly used server-side scripting language widely used in website development and data processing fields. In PHP, it is a very common requirement to sort the values ​​in an array by size. By using the built-in sort function, you can easily sort arrays. The following will introduce how to use PHP to sort the values ​​in an array by size, with specific code examples: 1. Sort the values ​​in the array in ascending order:

See all articles