JAVASCRIPT
Programmatically Set Multiple CSS Styles on a DOM Element
Learn how to apply multiple inline CSS properties to an HTML element directly using JavaScript's `element.style` object, enabling dynamic visual updates based on user interaction or application state.
const myStyledBox = document.getElementById('styledBox');
const applyStylesButton = document.getElementById('applyStylesBtn');
if (myStyledBox && applyStylesButton) {
applyStylesButton.addEventListener('click', () => {
// Set individual style properties
myStyledBox.style.backgroundColor = '#ffcc00'; // Amber
myStyledBox.style.padding = '15px';
myStyledBox.style.borderRadius = '8px';
myStyledBox.style.border = '2px solid #333';
myStyledBox.style.color = '#333';
myStyledBox.style.fontSize = '1.2em';
myStyledBox.textContent = 'Styles Applied!';
// For properties with hyphens (e.g., font-size), use camelCase
myStyledBox.style.transition = 'all 0.5s ease-in-out';
console.log('Styles applied to the box.');
});
}
/*
Example HTML and initial CSS:
<style>
#styledBox {
width: 150px;
height: 100px;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
margin-top: 10px;
text-align: center;
transition: all 0.5s ease-in-out; /* Initial transition for smoothness */
}
</style>
<button id="applyStylesBtn">Apply Styles</button>
<div id="styledBox">Initial State</div>
*/
How it works: This snippet demonstrates how to dynamically apply multiple inline CSS styles to an HTML element using JavaScript's `element.style` property. Each CSS property, written in camelCase (e.g., `backgroundColor` instead of `background-color`), can be directly assigned a string value. This method is useful for making immediate visual changes to elements based on user interaction or application logic, providing fine-grained control over an element's appearance. While often used for simple changes, for complex styling, toggling CSS classes is generally preferred.