- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements