JAVASCRIPT

Change CSS Styles of Elements with JavaScript

Apply inline CSS styles to HTML elements directly using JavaScript's `element.style` property to modify appearance based on user interactions or data changes.

function updateElementStyles(elementId, styles) {
  const element = document.getElementById(elementId);

  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  for (const [property, value] of Object.entries(styles)) {
    // CSS properties like 'background-color' become 'backgroundColor' in JS
    const jsProperty = property.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
    element.style[jsProperty] = value;
  }
  console.log(`Styles updated for element '${elementId}'.`);
}

// Example Usage:
// Assume HTML:
// <button id="myButton">Style Me</button>
// <div id="myBox" style="width: 100px; height: 100px; background-color: grey;"></div>

// Change button styles
updateElementStyles('myButton', {
  'background-color': '#007bff',
  'color': 'white',
  'padding': '10px 20px',
  'border-radius': '5px',
  'border': 'none',
  'cursor': 'pointer'
});

// Change box styles after a delay
setTimeout(() => {
  updateElementStyles('myBox', {
    'background-color': 'lightgreen',
    'width': '150px',
    'height': '150px',
    'border': '2px solid green'
  });
}, 1500);

// Attach event listener for interactive styling
const interactiveButton = document.getElementById('myButton');
if (interactiveButton) {
  interactiveButton.addEventListener('mouseover', () => {
    updateElementStyles('myButton', { 'opacity': '0.8' });
  });
  interactiveButton.addEventListener('mouseout', () => {
    updateElementStyles('myButton', { 'opacity': '1' });
  });
}
How it works: This snippet demonstrates how to dynamically modify the CSS styles of an HTML element using JavaScript's `element.style` property. It provides a function that accepts an element ID and an object of CSS properties and values. The function iterates through the provided styles, converting kebab-case CSS properties (e.g., `background-color`) to their camelCase JavaScript equivalents (e.g., `backgroundColor`) before applying them. This is essential for interactive UIs, themes, or responding to user actions by changing an element's visual appearance directly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs