JAVASCRIPT
Updating DOM Element Attributes, Classes, and Styles
Discover how to modify HTML element properties like `src`, `href`, `class`, and inline styles dynamically using JavaScript, enhancing interactivity and visual presentation.
document.addEventListener('DOMContentLoaded', () => {
const myImage = document.getElementById('myImage');
const myButton = document.getElementById('myButton');
if (myImage) {
// Update an attribute
myImage.src = 'https://via.placeholder.com/150/FF0000/FFFFFF?text=NewImage';
myImage.alt = 'A dynamically loaded image';
// Add a class
myImage.classList.add('highlight');
// Remove a class
myImage.classList.remove('default-border');
// Set an inline style
myImage.style.border = '2px solid blue';
myImage.style.transition = 'all 0.3s ease-in-out';
}
if (myButton) {
myButton.addEventListener('click', () => {
myButton.textContent = 'Clicked!';
myButton.style.backgroundColor = 'lightgreen';
});
}
});
How it works: This snippet illustrates various ways to modify an existing DOM element. It shows how to change an `<img>` element's `src` and `alt` attributes, add and remove CSS classes using `classList`, and apply inline styles directly via the `style` property. It also includes an example of modifying button text and style on click.