JAVASCRIPT

Programmatically Change Inline Styles of an Element

Discover how to directly manipulate an element's inline CSS properties using JavaScript, offering precise control over its visual presentation.

function updateElementStyles(elementId, styles) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error('Element not found.');
    return;
  }

  for (const prop in styles) {
    if (Object.prototype.hasOwnProperty.call(styles, prop)) {
      // CSS property names with hyphens become camelCase in JavaScript
      element.style[prop] = styles[prop];
    }
  }
  console.log(`Styles applied to #${elementId}:`, styles);
}

// Example Usage:
// <div id="myStyledDiv" style="border: 1px solid black; padding: 10px;">Hello</div>
// updateElementStyles('myStyledDiv', {
//   backgroundColor: '#f0f0f0',
//   fontSize: '20px',
//   color: 'red',
//   marginTop: '20px'
// });
How it works: This function allows you to change the inline styles of any DOM element directly using JavaScript. It takes an element's ID and an object of style properties and values. CSS property names like `background-color` are converted to camelCase (`backgroundColor`) when accessed via `element.style`. This method provides granular control over an element's appearance without relying on CSS classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs