JAVASCRIPT
Dynamically Change Inline CSS Styles
Learn how to directly modify an HTML element's inline CSS properties using JavaScript, enabling precise and dynamic styling adjustments.
function setElementStyles(elementId, stylesObject) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found for styling:', elementId);
return;
}
for (const property in stylesObject) {
if (Object.prototype.hasOwnProperty.call(stylesObject, property)) {
// Convert camelCase to kebab-case if necessary for direct style string assignment
// Or simply assign to the camelCase JS property which is more common and safer
element.style[property] = stylesObject[property];
}
}
console.log(`Styles applied to element '${elementId}'.`);
}
// Example usage:
// HTML structure: <div id="myBox">Hello</div>
// setElementStyles('myBox', {
// backgroundColor: 'lightblue',
// border: '2px solid navy',
// padding: '15px',
// fontSize: '20px',
// color: '#333'
// });
// Change a single style later:
// document.getElementById('myBox').style.backgroundColor = 'lightgreen';
How it works: This snippet demonstrates how to dynamically modify the inline CSS styles of an HTML element using JavaScript. It takes an element ID and an object containing CSS property-value pairs. The function then iterates through the object and assigns each style value to the corresponding `element.style` property. This method allows for precise control over an element's appearance without directly manipulating CSS classes, making it ideal for unique or programmatic style adjustments.