JAVASCRIPT
Modifying DOM Element Styles and Classes
Discover how to programmatically change an element's CSS styles and manipulate its class list using JavaScript for dynamic visual updates.
function updateElementAppearance(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
// 1. Modifying inline styles
element.style.backgroundColor = '#f0f0f0';
element.style.padding = '10px';
element.style.border = '1px solid #ccc';
element.style.color = '#333';
// 2. Manipulating CSS classes
// Add a class
element.classList.add('highlight');
// Remove a class
element.classList.remove('default-style');
// Toggle a class (add if not present, remove if present)
element.classList.toggle('active');
// Check if a class exists
if (element.classList.contains('highlight')) {
console.log('Element has highlight class.');
}
}
// Example Usage:
// Assume you have an element like: <div id="myDiv" class="default-style">Hello</div>
updateElementAppearance('myDiv');
How it works: This code illustrates two primary ways to alter an element's appearance. It shows how to directly set inline CSS properties via the `style` object and how to manage CSS classes using the `classList` API (`add`, `remove`, `toggle`, `contains`). These methods are crucial for creating dynamic visual feedback and responsive designs.