JAVASCRIPT

Dynamically Change Element Styles

Learn to modify individual CSS properties of HTML elements directly through JavaScript's `style` property for dynamic visual updates and interactive styling.

function updateElementStyle(elementId, styleProperty, value) {
  const element = document.getElementById(elementId);
  if (element) {
    // Note: CSS property names like 'background-color' become 'backgroundColor' in JavaScript
    element.style[styleProperty] = value;
    console.log(`Style property '${styleProperty}' set to '${value}' for element '${elementId}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

function getElementStyle(elementId, styleProperty) {
  const element = document.getElementById(elementId);
  if (element) {
    // For inline styles, use .style property
    const inlineValue = element.style[styleProperty];
    console.log(`Inline style '${styleProperty}' on '${elementId}': '${inlineValue}'.`);

    // For computed (final) styles, use getComputedStyle
    const computedStyle = window.getComputedStyle(element);
    const computedValue = computedStyle[styleProperty];
    console.log(`Computed style '${styleProperty}' on '${elementId}': '${computedValue}'.`);

    return { inline: inlineValue, computed: computedValue };
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
    return null;
  }
}

// Example usage:
// Assume you have an HTML element: <div id="myStyledDiv" style="width: 100px; height: 100px; background-color: blue;"></div>

// Change background color:
updateElementStyle('myStyledDiv', 'backgroundColor', 'red');

// Change width and add a border:
updateElementStyle('myStyledDiv', 'width', '200px');
updateElementStyle('myStyledDiv', 'border', '2px solid green');

// Get current styles:
const colorInfo = getElementStyle('myStyledDiv', 'backgroundColor');
const widthInfo = getElementStyle('myStyledDiv', 'width');
How it works: This snippet demonstrates how to directly manipulate an element's inline CSS styles using JavaScript's `style` property. CSS properties like `background-color` are accessed in camelCase as `backgroundColor`. The `updateElementStyle` function sets a specific style, while `getElementStyle` shows how to retrieve both inline styles (`element.style`) and the final, computed style of an element (including styles from stylesheets) using `window.getComputedStyle()`. This is essential for creating dynamic visual effects and responsive UIs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs