JAVASCRIPT
Update Element Attributes and Toggle CSS Classes
Discover how to programmatically modify HTML element attributes and dynamically add or remove CSS classes using JavaScript's DOM manipulation methods for interactive web UIs.
function updateElementProperties(selector, newAttributes = {}, classToToggle = null) {
const element = document.querySelector(selector);
if (!element) {
console.error(`Element with selector '${selector}' not found.`);
return;
}
// Update attributes
for (const key in newAttributes) {
if (Object.hasOwnProperty.call(newAttributes, key)) {
element.setAttribute(key, newAttributes[key]);
}
}
// Toggle CSS class
if (classToToggle) {
element.classList.toggle(classToToggle);
}
}
// Example Usage:
// <img id="myImage" src="old.jpg" alt="Old Image">
// <button id="myButton" class="btn active">Toggle Me</button>
// updateElementProperties('#myImage', { src: 'new.png', alt: 'New Image Title', 'data-status': 'updated' });
// updateElementProperties('#myButton', {}, 'active'); // Toggles 'active' class
How it works: This snippet provides a flexible function to modify an element's attributes and toggle its CSS classes. It takes a CSS selector to find the element, an object for new attributes (which will overwrite existing ones or add new ones), and an optional class name to toggle, enabling dynamic styling and behavior changes.