How to set attribute in loop from array JavaScript?


Let’s say we are required to write a function that takes in an array and changes the id attribute of first n divs present in a particular DOM according to corresponding values of this array, where n is the length of the array.

We will first select all divs present in our DOM, iterate over the array we accepted as one and only argument and assign the corresponding id to each div −

The code for doing the same is −

const array = ['navbar', 'sidebar', 'section1', 'section2', 'footer'];
const changeDivId = (arr) => {
   const divsArray = document.querySelectorAll('div');
   arr.forEach((element, index) => {
      divsArray[index].id = element;
   });
};
changeDivId(array);

With this we can successfully map the elements of the array to the corresponding id of div.

Updated on: 18-Aug-2020

755 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements