JAVASCRIPT

Dynamically Apply and Retrieve Inline CSS Styles

Learn to programmatically set and retrieve individual inline CSS properties on any HTML element using its `style` property, offering direct control over visual presentation.

function manageElementStyles(elementId) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error('Element not found with ID:', elementId);
    return;
  }

  // 1. Set inline styles
  element.style.color = 'green';
  element.style.backgroundColor = '#f0f0f0';
  element.style.padding = '10px';
  element.style.border = '1px solid black';

  // 2. Get inline styles (returns string value)
  const currentColor = element.style.color;
  const currentBgColor = element.style.backgroundColor;

  console.log(`Current color: ${currentColor}`); // Will log 'green'
  console.log(`Current background color: ${currentBgColor}`); // Will log 'rgb(240, 240, 240)'

  // Important: This only retrieves styles explicitly set inline via JavaScript or style attribute.
  // It does NOT retrieve computed styles from CSS stylesheets.
  // For computed styles, use getComputedStyle(element).
}

// Usage:
// <p id="myStyledText">Some text to style</p>
// manageElementStyles('myStyledText');
How it works: This snippet illustrates how to directly manipulate an HTML element's inline CSS styles using its `style` property. You can set individual style properties like `color`, `backgroundColor`, or `padding` using camelCase for CSS property names. It also shows how to retrieve these inline-set styles. It's important to note that `element.style` only accesses styles explicitly defined as inline; to get styles applied via stylesheets, `window.getComputedStyle()` should be used.

Need help integrating this into your project?

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

Hire DigitalCodeLabs