JAVASCRIPT
Batch Update Styles and Attributes of Multiple Elements
Discover how to select multiple DOM elements using `querySelectorAll` and efficiently apply consistent style changes or update specific attributes using JavaScript loops.
/**
* Selects multiple elements and applies style or attribute changes.
* @param {string} selector CSS selector to target elements (e.g., '.my-class', 'div.item').
* @param {object} changes An object containing style properties or attribute key-value pairs.
* @param {'style'|'attribute'} type Specifies whether to apply 'style' or 'attribute' changes.
*/
function updateMultipleElements(selector, changes, type = 'style') {
const elements = document.querySelectorAll(selector);
if (!elements.length) {
console.warn(`No elements found matching selector: ${selector}`);
return;
}
elements.forEach(element => {
if (type === 'style') {
for (const prop in changes) {
if (Object.prototype.hasOwnProperty.call(changes, prop)) {
element.style[prop] = changes[prop];
}
}
} else if (type === 'attribute') {
for (const attr in changes) {
if (Object.prototype.hasOwnProperty.call(changes, attr)) {
element.setAttribute(attr, changes[attr]);
}
}
} else {
console.error(`Invalid type specified: ${type}. Use 'style' or 'attribute'.`);
}
});
}
// --- Example Usage ---
// Assume HTML:
// <div class="card product" data-status="new">Item A</div>
// <div class="card product" data-status="sale">Item B</div>
// <div class="card service" data-status="new">Service C</div>
// 1. Update styles for all elements with class 'product'
updateMultipleElements('.product', {
backgroundColor: '#e6f7ff',
border: '1px solid #91d5ff',
padding: '10px'
}, 'style');
// 2. Update a custom data attribute for elements with class 'card' and data-status='new'
updateMultipleElements('.card[data-status="new"]', {
'data-processed': 'true'
}, 'attribute');
// 3. Change 'title' attribute for all divs
updateMultipleElements('div', {
title: 'This is a dynamically updated title.'
}, 'attribute');
How it works: The `updateMultipleElements` function allows you to target a group of elements using a CSS selector and apply either multiple CSS styles or multiple HTML attributes to all of them simultaneously. It iterates over the selected elements, making it efficient for bulk updates, and distinguishes between style and attribute modifications. This is very useful for applying consistent changes across many similar elements.