How to set attribute in loop from array JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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;

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

Published on 18-Aug-2020 10:42:36