Table of Contents
By iterating through for loop
grammar
algorithm
Example
Use Array.from() function
Home Web Front-end JS Tutorial Fastest way to convert JavaScript NodeList to Array

Fastest way to convert JavaScript NodeList to Array

Aug 31, 2023 pm 09:01 PM

将 JavaScript NodeList 转换为数组的最快方法

In this tutorial, we will learn the fastest way to convert JavaScript NodeList to Array. NodeList is an array-like structure; it is a collection of DOM (Document Object Model) elements. However, array methods like "map( )", "filter( )" and "slice( )" cannot be used on NodeList objects.

There are many ways to convert a NodeList to an Array, but this task can be accomplished faster using these two methods -

  • By iterating through for loop

  • Use Array.from( ) function

By iterating through for loop

In JavaScript, we can use a for loop to iterate over a NodeList to get all elements to perform a specific task. So, by iterating over the NodeList, we copy all the elements of the NodeList in the array.

grammar

const len = nodeList.length;
const arr = Array(len);
for (var i = 0 ; i != len ; i++) {
   arr[i] = nodeList[i];
}
Copy after login

We save the length of nodeList in a variable and declare an array of that size. When we know the array size, it is better to declare a fixed size array. Then we use a for loop to assign values ​​in the array.

algorithm

  • Step 1 - Store the length of nodeList in the len variable.

  • Step 2 - Declare an array of size len.

  • Step 3 - In the for loop, initialize the counter variable "i" with the value 0.

  • Step 3.1 - Iterate the loop until "i" is not equal to len.

  • Step 3.2 - In the update condition, increase "i" by 1.

  • Step 3.3 - In the for loop body, assign the value of the i-th index of NodeList to the i-th index of the array.

    < /里>

Example

In the following example, using the Document method document.querySelectorAll(), we get a NodeList of type selector "div". We are converting this NodeList to an array.

<html>
<body>
   <h2> Convert JavaScript NodeList to Array </h2>
   <div> <p> This is paragraph of first 'div' element </p> </div>
   <div> <p> This is paragraph of second 'div' element </p> </div>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      output.innerHTML = " <p> This is paragraph of third 'div' element </p> "
      output.innerHTML += " <b> Output of <i> NodeList </i> <b> <br> <br> ";
      
      //get NodeList of 'div' elements
      const nodeList = document.querySelectorAll('div');
      
      //Display output of NodeList
      output.innerHTML += nodeList + "<br> <br>";
      output.innerHTML += "<b> Output of <i> Array </i> <b> <br> <br>";
      
      //save length of NodeList
      const len = nodeList.length;
      
      //Declare array of size len
      const arr = Array(len);
      
      //This for loop will convert NodeList to Array
      for (var i = 0 ; i != len ; i++) {
         arr[i] = nodeList[i];
      }
      
      //Display output of Array
      output.innerHTML += arr;
   </script>
</body>
</html>
Copy after login

In the above code, users can see that we use a for loop to create an actual array from the NodeList. We use const to save the length of the NodeList in ‘len’ and declare an array of size ‘len’; this will make our operation faster.

We have 3 "div" elements. Hence, we get an array of size 3 as shown in the output.

Use Array.from() function

This method can be used to create an Array instance of an iterable object or an array-like object. We are converting a NodeList, which has a similar structure to an array.

Using ES6 (ECMAScript 6), we can get an array from a NodeList very easily using the Array.from() function. If we don't want to iterate over the NodeList and just want to convert it, then this will be the fastest way.

grammar

const nodeList = document.querySelectorAll('p');
let arr = Array.from(nodeList);
Copy after login

Here, we create a NodeList of type selector "p" using document.querySelectorAll() of Document method. We pass this NodeList as a parameter into the Array.from() function. This function returns an array. We only need one line of code to convert it to an array, which makes it easy to remember and understand.

Example

In the following example, we create a NodeList of type selector "p". We convert this NodeList to an array using the Array.from() function.

<html>
<body>
   <h2> Convert JavaScript NodeList to Array </h2>
   <p> We are here to teach you various concepts of Computer Science through our articles.</p>
   <p>Stay connected with us for such useful content.</p>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      output.innerHTML = " <b> Output of <i> NodeList </i> <b> <br> <br> ";
      
      //get NodeList of 'p' elements
      const nodeList = document.querySelectorAll('p');
      
      //Display output of NodeList
      output.innerHTML += nodeList + "<br> <br>";
      output.innerHTML += " <b> Output of <i> Array </i> <b> <br> <br> ";
      
      //This will convert NodeList to Array
      let arr = Array.from(nodeList);
      
      //Display output of Array
      output.innerHTML += arr;
   </script>
</body>
</html>
Copy after login

In the above output, the user sees that we got an array containing 2 "p" elements. Therefore, our NodeList is successfully converted to an array using only one function call.

Note - The above method works well in all modern browsers but may not work properly in older browsers.

We have learned to convert NodeList to Array. The first way is to use a for loop by iterating over the NodeList. The second way is to use the Array.from() method. When the user only wants to convert the NodeList, rather than iterate over it, it is recommended to use the Array.from() method.

The above is the detailed content of Fastest way to convert JavaScript NodeList to Array. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles