JAVASCRIPT
Update Element Styles and Attributes
Master changing an existing DOM element's inline CSS styles and HTML attributes programmatically with JavaScript for dynamic UI updates and interactivity.
const targetElement = document.getElementById('myUniqueElement');
if (targetElement) {
// Change inline styles
targetElement.style.backgroundColor = 'lightcoral';
targetElement.style.fontSize = '20px';
targetElement.style.border = '2px dashed blue';
// Update standard HTML attributes
targetElement.setAttribute('data-active', 'true');
targetElement.title = 'This element is now active!';
// Add a class for more complex styling
targetElement.classList.add('highlighted');
} else {
console.warn('Element with ID "myUniqueElement" not found.');
}
How it works: This code targets an element by its unique ID. If the element exists, it modifies its inline CSS properties like `backgroundColor`, `fontSize`, and `border` directly. It also updates custom HTML attributes using `setAttribute()` and standard ones like `title`. Additionally, it adds a new class to the element's `classList`, enabling class-based styling.