JAVASCRIPT
Modify DOM Element Attributes and Styles
Discover how to programmatically change HTML attributes like `src` or `href`, and update CSS styles directly on DOM elements using JavaScript's `setAttribute`, `removeAttribute`, `classList`, and `style` properties.
function updateElementProperties(elementId) {
const element = document.getElementById(elementId);
if (element) {
// 1. Modifying standard HTML attributes
if (element.tagName === 'IMG') {
element.setAttribute('src', 'https://via.placeholder.com/150');
element.setAttribute('alt', 'Updated Placeholder Image');
} else if (element.tagName === 'A') {
element.setAttribute('href', 'https://www.example.com');
element.textContent = 'Visit Example.com';
}
// 2. Toggling/Adding/Removing CSS classes
element.classList.add('highlight'); // Add a class
element.classList.remove('inactive'); // Remove a class
element.classList.toggle('active'); // Toggle a class
// 3. Modifying inline CSS styles
element.style.backgroundColor = '#f0f8ff'; // AliceBlue
element.style.padding = '15px';
element.style.border = '1px solid #ccc';
// 4. Removing attributes
element.removeAttribute('data-old-attribute');
console.log(`Element '${elementId}' properties updated.`);
} else {
console.error(`Element with ID '${elementId}' not found.`);
}
}
// Example Usage (assuming these elements exist in HTML):
// <img id="myImage" src="old.jpg" alt="Old Image" data-old-attribute="value">
// <a id="myLink" href="#">Old Link</a>
// <div id="myDiv" class="inactive" data-old-attribute="value">Some content</div>
updateElementProperties('myImage');
updateElementProperties('myLink');
updateElementProperties('myDiv');
How it works: This code snippet illustrates several ways to modify existing DOM elements. It shows how to change HTML attributes using `setAttribute()` (and remove them with `removeAttribute()`), which is useful for updating image sources, link targets, or custom data attributes. It also covers manipulating CSS classes with `classList.add()`, `classList.remove()`, and `classList.toggle()` for dynamic styling. Lastly, it demonstrates how to directly set inline CSS properties using the `element.style` object, providing granular control over an element's appearance.