
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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.
- Related Articles
- JavaScript recursive loop to sum all integers from nested array?
- How to convert Array to Set in JavaScript?
- Loop through a Set using Javascript
- How to use for...in statement to loop through an Array in JavaScript?
- Loop backward in array of objects JavaScript
- Extract unique objects by attribute from an array of objects in JavaScript
- Converting array to set in JavaScript
- How to break a loop in JavaScript?
- How to implement asynchronous loop in JavaScript?
- How to loop through an array in Java?
- How do we loop through array of arrays containing objects in JavaScript?
- How to remove “disabled” attribute from HTML input element using JavaScript?
- Loop through array and edit string JavaScript
- How to use nested while loop in JavaScript?
- How to use nested for loop in JavaScript?

Advertisements