JAVASCRIPT
Batch Updating Element Attributes and Styles
Discover a clean way to update multiple HTML attributes and CSS styles for a DOM element simultaneously using JavaScript. Improve readability and maintainability of your DOM manipulation code.
function updateElementProperties(elementId, attributes = {}, styles = {}) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found:', elementId);
return;
}
// Update attributes
for (const attrName in attributes) {
if (attributes.hasOwnProperty(attrName)) {
element.setAttribute(attrName, attributes[attrName]);
}
}
// Update styles
for (const styleProp in styles) {
if (styles.hasOwnProperty(styleProp)) {
element.style[styleProp] = styles[styleProp];
}
}
}
// Example usage:
// Assuming <div id="myDiv" class="old-class"></div>
// updateElementProperties('myDiv',
// { class: 'new-class another-class', 'data-status': 'active' },
// { backgroundColor: 'lightblue', fontSize: '18px', border: '1px solid blue' }
// );
How it works: This function provides a convenient way to update an element's attributes and inline styles in a single call. It iterates through provided objects, setting each attribute with `setAttribute()` and each style property directly on the element's `style` object, simplifying bulk modifications.