How to iterate through all selected elements into an array ?

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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • Using while loop.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • Using forEach method.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    index = 0; 
    array = [ a, b, c, d, e ]; 
    array.forEach(myFunction); 
    function myFunction(item, index) { 
        console.log(item); 
    }

    chevron_right

    
    

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!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>

    chevron_right

    
    

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

    full-stack-img




    My Personal Notes arrow_drop_up

    Data Structure & Algorithms Lead (C++) Developer Student Club (Google) || MERN Stack Web Developer || Machine Learning Enthusiast || Skilled in C, C++, Java, Python, HTML, CSS, JS, React, NodeJS, Mongoose, Git among others

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.