Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Basic Example
Here's the HTML structure we'll work with:
<html>
<head>
<title>Setting Attributes in Loop</title>
</head>
<body>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<div>Fourth div</div>
<div>Fifth div</div>
<script>
const array = ['navbar', 'sidebar', 'section1', 'section2', 'footer'];
const changeDivId = (arr) => {
const divsArray = document.querySelectorAll('div');
arr.forEach((element, index) => {
if (divsArray[index]) {
divsArray[index].id = element;
}
});
};
changeDivId(array);
// Display the updated ids
const divs = document.querySelectorAll('div');
divs.forEach(div => {
console.log(`Div content: "${div.textContent}" - ID: "${div.id}"`);
});
</script>
</body>
</html>
Div content: "First div" - ID: "navbar" Div content: "Second div" - ID: "sidebar" Div content: "Third div" - ID: "section1" Div content: "Fourth div" - ID: "section2" Div content: "Fifth div" - ID: "footer"
Using setAttribute() Method
An alternative approach using the setAttribute() method for better clarity:
<html>
<head>
<title>Using setAttribute Method</title>
</head>
<body>
<div>Header</div>
<div>Main</div>
<div>Footer</div>
<script>
const setDivAttributes = (ids, attribute = 'id') => {
const divs = document.querySelectorAll('div');
ids.forEach((value, index) => {
if (divs[index]) {
divs[index].setAttribute(attribute, value);
}
});
};
const idArray = ['header-main', 'content-area', 'footer-section'];
setDivAttributes(idArray);
// Verify the results
document.querySelectorAll('div').forEach(div => {
console.log(`Element: ${div.textContent} | ID: ${div.id}`);
});
</script>
</body>
</html>
Element: Header | ID: header-main Element: Main | ID: content-area Element: Footer | ID: footer-section
Setting Multiple Attributes
You can extend this concept to set multiple attributes from objects:
<html>
<head>
<title>Multiple Attributes Example</title>
</head>
<body>
<div>Card 1</div>
<div>Card 2</div>
<div>Card 3</div>
<script>
const setMultipleAttributes = (attributeObjects) => {
const divs = document.querySelectorAll('div');
attributeObjects.forEach((attrs, index) => {
if (divs[index]) {
Object.keys(attrs).forEach(key => {
divs[index].setAttribute(key, attrs[key]);
});
}
});
};
const attributeData = [
{ id: 'card1', class: 'primary-card', 'data-type': 'featured' },
{ id: 'card2', class: 'secondary-card', 'data-type': 'regular' },
{ id: 'card3', class: 'tertiary-card', 'data-type': 'special' }
];
setMultipleAttributes(attributeData);
// Display results
document.querySelectorAll('div').forEach(div => {
console.log(`ID: ${div.id}, Class: ${div.className}, Data-type: ${div.getAttribute('data-type')}`);
});
</script>
</body>
</html>
ID: card1, Class: primary-card, Data-type: featured ID: card2, Class: secondary-card, Data-type: regular ID: card3, Class: tertiary-card, Data-type: special
Key Points
- Always check if the element exists before setting attributes to avoid errors
- Use
forEach()with index parameter to iterate through both array and elements -
setAttribute()is more explicit than direct property assignment - This approach works with any attribute, not just
id
Conclusion
Setting attributes in a loop from an array is straightforward using querySelectorAll() and forEach(). Always include safety checks to ensure elements exist before modifying their attributes.
