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.
var myElement = document.getElementById("element-id");
var myElements = document.getElementsByTagName("div");
var myElements = document.getElementsByClassName( "element-class");
var myElements = document.querySelectorAll("div.class-name");
The second step involves iterating over the array. There are several ways to do this:
In this approach, select all the
div elements from the first container, add them to the second container.
Before clicking on the button:
After clicking on the button:
To convert a NodeList to an array:
var divsArr = Array.prototype.slice.call(divs);
- What are the efficient ways to iterate over all DOM elements ?
- Iterate associative array using foreach loop in PHP
- How to get all selected checkboxes in an array using jQuery ?
- Iterate over a set in Python
- Iterate over a list in Python
- Iterate over a dictionary in Python
- How to iterate over rows in Pandas Dataframe
- Iterate over characters of a string in Python
- Different ways to iterate over rows in Pandas Dataframe
- How to iterate over the keys and values with ng-repeat in AngularJS ?
- How to iterate over filtered (ng-repeat filter) collection of objects in AngularJS ?
- HTML | selected Attribute
- AngularJS | ng-selected Directive
- jQuery | :selected Selector
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.