Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to add/remove an element to/from the array in bash?
Next article icon

How to iterate through all selected elements into an array ?

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
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);


Next Article
How to add/remove an element to/from the array in bash?
author
verma_anushka
Improve
Article Tags :
  • JavaScript
  • Technical Scripter
  • Web Technologies
  • JavaScript-Questions
  • Technical Scripter 2019

Similar Reads

  • How to get all selected checkboxes in an array using jQuery ?
    In this article, we are going to discuss various methods to get all the selected checkboxes in an array using jQuery. Several ways of doing this in jQuery are explained in detail with their practical implementation using code examples. Table of Content Using the array.push() method with each() metho
    4 min read
  • How to bind select element to an object in Angular ?
    AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. An Angular service is a broad category that consists of an
    4 min read
  • How to add/remove an element to/from the array in bash?
    If we want to operate an element by adding and removing from the array using the bash script, then we can create a custom bash script that will perform the options of adding and removing the elements from the array. Example: Choose an option: 1. Print Rainbow Colors 2. Add a Color to the Rainbow 3.
    6 min read
  • How to transform a JavaScript iterator into an array ?
    The task is to convert an iterator into an array, this can be performed by iterating each value of the iterator and storing the value in another array. These are the following ways we can add an iterator to an array: Table of Content Using Symbol iterator PropertyUsing Array.from MethodUsing the Spr
    3 min read
  • How to loop through input elements in jQuery ?
    In this article, we will learn how to loop through input elements and display their current values in jQuery. This can be done using two approaches: Approach 1: In this approach, we will iterate over every input type which is of text type by using input[type=text] as the selector. Next, we will use
    2 min read
  • How to Select a Random Element from Array in TypeScript ?
    We are given an array in TypeScript and we have to select a random element every time the code runs. It will automatically select a new random element every time and return it. The below approaches can be used to accomplish this task: Table of Content Using Math.random() functionUsing splice() metho
    2 min read
  • How to Loop Through an Array in JavaScript?
    Here are the various ways to loop through an array in JavaScript 1. Using for LoopThe for loop is one of the most used ways to iterate over an array. It gives you complete control over the loop, including access to the array index, which can be useful when you need to modify elements or perform othe
    4 min read
  • JavaScript - How to Remove an Element from an Array?
    Removing elements from an array is a fundamental operation in JavaScript, essential for data manipulation, filtering, and transformation. This guide will explore different methods to efficiently remove elements from an array, enhancing your understanding and capability in handling arrays. 1. Using p
    3 min read
  • How to Select a Range of Elements using jQuery ?
    Given an HTML document with a range of similar elements and the task is to select a range of those elements with the help of JavaScript. There are two approaches that are discussed below with an example. Approach 1: First, select all elements of class = 'child' by jQuery selector then use slice() me
    2 min read
  • How to iterate over Map elements in JavaScript ?
    Map() is very useful in JavaScript it organises elements into key-value pairs. This method iterates over each element in an array and applies a callback function to it, allowing for modifications before returning the updated array." The Map() keyword is used to generate the object. The map() method
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences