JAVASCRIPT

Dynamically Modify Element Inline Styles

Learn how to directly change an HTML element's visual presentation by setting or updating its inline CSS properties using JavaScript.

function applyInlineStyles(selector, styles) {
  const element = document.querySelector(selector);
  if (element) {
    for (const prop in styles) {
      if (Object.hasOwnProperty.call(styles, prop)) {
        // JavaScript style properties are camelCase (e.g., 'fontSize' for 'font-size')
        element.style[prop] = styles[prop];
      }
    }
    console.log(`Applied styles to element matching '${selector}'.`);
  } else {
    console.warn(`Element matching selector '${selector}' not found.`);
  }
}

// Usage example:
// Assuming <p id="styledParagraph">Hello World</p>
// Add to DOM for example:
document.addEventListener('DOMContentLoaded', () => {
  const p = document.createElement('p');
  p.id = 'styledParagraph';
  p.textContent = 'Hello World';
  document.body.appendChild(p);

  applyInlineStyles('#styledParagraph', {
    color: 'green',
    fontSize: '24px',
    fontWeight: 'bold',
    backgroundColor: '#eee'
  });

  // Change a single style after some time
  setTimeout(() => {
    applyInlineStyles('#styledParagraph', {
      color: 'purple',
      textDecoration: 'underline'
    });
  }, 2000);
});
How it works: This snippet demonstrates how to directly manipulate an HTML element's inline CSS styles using JavaScript. The `element.style` property provides access to the inline style declaration of an element, where individual CSS properties can be set as JavaScript properties. It's important to note that CSS property names with hyphens (e.g., `font-size`) are converted to camelCase in JavaScript (e.g., `fontSize`). This method is useful for immediate visual changes but for more complex styling, managing CSS classes is generally preferred.

Need help integrating this into your project?

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

Hire DigitalCodeLabs