JAVASCRIPT

Programmatically Update an Element's Inline CSS Styles

Understand how to modify an HTML element's inline CSS properties directly through JavaScript using the `style` object, allowing for precise dynamic styling adjustments.

function updateElementStyle(elementId, property, value) {
  const element = document.getElementById(elementId);
  if (element) {
    element.style[property] = value;
    return true;
  }
  return false;
}

// Example Usage:
// Assume you have a div with id="styledDiv"
// <div id="styledDiv" style="width: 100px; height: 100px; background-color: red;"></div>

// Update background color
// updateElementStyle('styledDiv', 'backgroundColor', 'blue');

// Update width and add a border
// updateElementStyle('styledDiv', 'width', '200px');
// updateElementStyle('styledDiv', 'border', '22px solid green');
How it works: Every HTML element in the DOM has a `style` property, which is an object representing its inline CSS styles. This function allows you to directly set or change any CSS property on an element by treating the property name (in camelCase, e.g., `backgroundColor` for `background-color`) as a key and assigning a new string value.

Need help integrating this into your project?

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

Hire DigitalCodeLabs