How to iterate through all selected elements into an array ? - GeeksforGeeks

19 Feb, 2020
The task is to add all the selected HTML elements into an array and iterate through the array. To achieve this, the first step is to select all the desired elements. There are several ways to do this.
Finding HTML elements by id:var myElement = document.getElementById("element-id");
var myElement = document.getElementById("element-id");
Finding HTML elements by tag name:var myElements = document.getElementsByTagName("div");
var myElements = document.getElementsByTagName("div");
Finding HTML elements by class name:var myElements = document.getElementsByClassName( "element-class");
var myElements = document.getElementsByClassName( "element-class");
Finding HTML elements by CSS selectors:var myElements = document.querySelectorAll("div.class-name");The second step involves iterating over the array. There are several ways to do this:
var myElements = document.querySelectorAll("div.class-name");
The second step involves iterating over the array. There are several ways to do this:
Using for loop.array = [ a, b, c, d, e ];for (index = 0; index < array.length; index++) {     console.log(array[index]); }
array = [ a, b, c, d, e ];for (index = 0; index < array.length; index++) {     console.log(array[index]); }
Using while loop.index = 0; array = [ a, b, c, d, e ]; while (index < array.length) {     console.log(array[index]);     index++; }
index = 0; array = [ a, b, c, d, e ]; while (index < array.length) {     console.log(array[index]);     index++; }
Using forEach method.index = 0; array = [ a, b, c, d, e ]; array.forEach(myFunction); function myFunction(item, index) {     console.log(item); }Approach:First use the querySelectorAll selector to get all the elements. Then, use the forEach() and cloneNode() methods to iterate over the elements.Example 1:In this approach, select all the div elements from the first container, add them to the second container.
index = 0; array = [ a, b, c, d, e ]; array.forEach(myFunction); function myFunction(item, index) {     console.log(item); }
Approach:First use the querySelectorAll selector to get all the elements. Then, use the forEach() and cloneNode() methods to iterate over the elements.
Example 1:In this approach, select all the div elements from the first container, add them to the second container.
Use querySelectorAll() to get all the div elements in the first container(list-1).
Click on the button(Click Me!) to select the elements and append them to the second container.
Select the second container(list-2) using querySelector().
Loop through the all the div elements using the forEach() method.
Clone each div using the cloneNode() method and add it to the second container using appendChild()<!DOCTYPE html><html>  <head>    <title>Demo</title>    <style>        /* Basic styling */                  html {            text-align: center;            display: block;            margin: 0 auto;        }                  h1 {            color: green;            text-align: center;        }                  .list-1,        .list-2 {            width: 240px;            height: 120px;            text-align: center;            display: block;            margin: 0 auto;            background: lightgreen;            border: 1px solid #000;        }                  div,        button {            width: 80px;            height: 20px;            margin: 14px 78px;            color: #fff;            background: green;            border: 1px solid #000;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <div class="list-1">        <!-- select elements from here -->        <div>Element 1</div>        <div>Element 2</div>        <div>Element 3</div>    </div>    <button>Click Me!</button>    <div class="list-2">        <!-- add the selected elements here -->    </div>    <script>        var divs = document.querySelectorAll('.list-1 > div');        var button = document.querySelector('button');        button.addEventListener("click", () => {            var list_2 = document.querySelector('.list-2');            divs.forEach((div) => {                list_2.appendChild(div.cloneNode(true));            })        });    </script></body>  </html>Output:Before clicking on the button:After clicking on the button:Additional note:querySelectorAll() is not a JavaScript method, it is a browser API that lets you access DOM elements. This method returns a Node List and not an array. The difference between a NodeList and an Array is that a NodeList is a language-agnostic way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff.To convert a NodeList to an array:var divsArr = Array.prototype.slice.call(divs);My Personal Notes
arrow_drop_upSave
<!DOCTYPE html><html>  <head>    <title>Demo</title>    <style>        /* Basic styling */                  html {            text-align: center;            display: block;            margin: 0 auto;        }                  h1 {            color: green;            text-align: center;        }                  .list-1,        .list-2 {            width: 240px;            height: 120px;            text-align: center;            display: block;            margin: 0 auto;            background: lightgreen;            border: 1px solid #000;        }                  div,        button {            width: 80px;            height: 20px;            margin: 14px 78px;            color: #fff;            background: green;            border: 1px solid #000;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <div class="list-1">        <!-- select elements from here -->        <div>Element 1</div>        <div>Element 2</div>        <div>Element 3</div>    </div>    <button>Click Me!</button>    <div class="list-2">        <!-- add the selected elements here -->    </div>    <script>        var divs = document.querySelectorAll('.list-1 > div');        var button = document.querySelector('button');        button.addEventListener("click", () => {            var list_2 = document.querySelector('.list-2');            divs.forEach((div) => {                list_2.appendChild(div.cloneNode(true));            })        });    </script></body>  </html>
Output:Before clicking on the button:
After clicking on the button:
Additional note:querySelectorAll() is not a JavaScript method, it is a browser API that lets you access DOM elements. This method returns a Node List and not an array. The difference between a NodeList and an Array is that a NodeList is a language-agnostic way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff.
To convert a NodeList to an array:
var divsArr = Array.prototype.slice.call(divs);
JavaScript-Misc
Picked
Technical Scripter 2019
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?