JAVASCRIPT
Dynamically Change Inline CSS Styles of an Element
Explore how to programmatically modify the inline CSS properties of any HTML element directly through JavaScript, enabling dynamic styling changes.
function applyInlineStyles(elementId, styles = {}) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
for (const prop in styles) {
// Convert camelCase JS property to kebab-case if necessary for some specific cases
// (though element.style usually handles camelCase automatically for CSS properties)
element.style[prop] = styles[prop];
}
console.log(`Inline styles applied to element '${elementId}'.`);
}
function removeInlineStyle(elementId, property) {
const element = document.getElementById(elementId);
if (element) {
element.style[property] = ''; // Setting to empty string removes the inline style
console.log(`Inline style property '${property}' removed from element '${elementId}'.`);
} else {
console.warn(`Element with ID '${elementId}' not found.`);
}
}
// Example usage:
// Assume <div id="myStyledDiv" style="color: blue;">Hello</div>
// applyInlineStyles('myStyledDiv', {
// backgroundColor: 'yellow',
// fontSize: '20px',
// border: '1px solid black'
// });
// setTimeout(() => removeInlineStyle('myStyledDiv', 'backgroundColor'), 2000);
How it works: This snippet shows how to directly manipulate an element's inline CSS styles using the `element.style` property. You can set individual CSS properties (using camelCase for JavaScript) directly, such as `element.style.backgroundColor = 'red'`. Setting a style property to an empty string (`''`) will effectively remove that inline style. This provides granular control over an element's appearance without modifying CSS classes.