Open In App

How to iterate through all selected elements into an array ?

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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");
  • Finding HTML elements by tag name:
var myElements = document.getElementsByTagName("div");
  • Finding HTML elements by class name:
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:

Using for loop:

javascript




array = [ a, b, c, d, e ];
for (index = 0; index < array.length; index++) { 
    console.log(array[index]); 
}


Using while loop:

javascript




index = 0; 
array = [ a, b, c, d, e ]; 
while (index < array.length) { 
    console.log(array[index]); 
    index++; 
}


Using forEach method:

javascript




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()

html




<!DOCTYPE html>
<html>
<head>
<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: 

How to iterate through all selected elements into an array ?

How to iterate through all selected elements into an array ?

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);


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads