← Back to all snippets
JAVASCRIPT

Dynamically Updating Multiple Inline CSS Styles

Explore how to programmatically change an element's inline CSS styles using JavaScript's `style` property, ideal for dynamic styling based on user interaction or data changes.

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

document.getElementById('applyStyleBtn').addEventListener('click', () => {
  styledBox.style.backgroundColor = '#bbdefb';
  styledBox.style.padding = '20px';
  styledBox.style.borderRadius = '8px';
  styledBox.style.boxShadow = '0 4px 8px rgba(0,0,0,0.1)';
  styledBox.style.transition = 'all 0.3s ease-in-out';
  console.log('Element styles updated.');
});

document.getElementById('resetStyleBtn').addEventListener('click', () => {
  styledBox.style = ''; // Clears all inline styles applied directly via 'style' property
  console.log('Element styles reset.');
});

// Initial state (optional, for demonstration)
styledBox.style.width = '200px';
styledBox.style.height = '100px';
styledBox.style.border = '1px solid #ccc';
styledBox.textContent = 'Click buttons to change styles!';
How it works: This snippet shows how to modify multiple inline CSS properties of an element directly via its `style` property. It sets `backgroundColor`, `padding`, `borderRadius`, `boxShadow`, and `transition` on a button click. Another button demonstrates how to clear all inline styles by setting the `style` property to an empty string. This is useful for precise, on-the-fly style adjustments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs