JAVASCRIPT

Dynamically Apply Inline Styles to Elements

Explore how to directly modify the inline CSS styles of an HTML element using JavaScript, enabling dynamic visual changes and interactive effects on the fly.

const myStyledBox = document.getElementById('myStyledBox');

if (myStyledBox) {
  myStyledBox.style.backgroundColor = '#f0f8ff'; // AliceBlue
  myStyledBox.style.border = '2px solid #4682b4'; // SteelBlue
  myStyledBox.style.padding = '20px';
  myStyledBox.style.margin = '15px 0';
  myStyledBox.style.borderRadius = '8px';
  myStyledBox.style.boxShadow = '0 4px 8px rgba(0,0,0,0.1)';
  myStyledBox.style.fontSize = '1.2em'; // Note camelCase for 'font-size'
  myStyledBox.style.color = '#333';
}
How it works: This code snippet shows how to directly manipulate the inline styles of an HTML element using JavaScript. By accessing the `style` property of a DOM element, you can set various CSS properties. CSS property names that use hyphens (e.g., `background-color`) are converted to camelCase in JavaScript (e.g., `backgroundColor`). This method is useful for immediate, dynamic style changes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs