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:
Using while loop:
Using forEach method:
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()
To convert a NodeList to an array:
var divsArr = Array.prototype.slice.call(divs);
Please Login to comment...