JAVASCRIPT
Dynamically Change Element Inline Styles
Learn to directly manipulate an element's inline CSS styles using JavaScript, changing properties like color, font size, and display for instant visual updates.
const boxElement = document.getElementById('styledBox');
// Change background color
boxElement.style.backgroundColor = '#FFDDC1';
// Change font size and text color
boxElement.style.fontSize = '20px';
boxElement.style.color = 'darkgreen';
// Add a border
boxElement.style.border = '2px solid #FFA07A';
// Hide an element
// boxElement.style.display = 'none';
// Set multiple styles concisely using Object.assign
Object.assign(boxElement.style, {
padding: '15px',
borderRadius: '8px',
boxShadow: '0 4px 8px rgba(0,0,0,0.1)'
});
// Example HTML setup (not part of snippet, but for context):
// <div id="styledBox" style="width: 200px; height: 100px; background-color: lightgray; text-align: center; line-height: 100px;">Hello Styled Box</div>
How it works: This code demonstrates how to apply and modify inline CSS styles on an HTML element directly through JavaScript. By accessing the `style` property of an element, you can set various CSS properties using their camelCase JavaScript equivalents (e.g., `backgroundColor` for `background-color`). The `Object.assign` method offers a concise way to apply multiple styles at once, making it efficient for bulk style changes.