JAVASCRIPT

Programmatically Manage Inline CSS Styles

Learn to directly apply and remove individual CSS properties to any DOM element using JavaScript, providing precise control over element presentation without modifying stylesheets.

function setInlineStyle(elementId, property, value) {
  const element = document.getElementById(elementId);
  if (element) {
    element.style[property] = value;
    console.log(`Set inline style '${property}: ${value}' for element ID '${elementId}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

function removeInlineStyle(elementId, property) {
  const element = document.getElementById(elementId);
  if (element) {
    element.style.removeProperty(property);
    console.log(`Removed inline style property '${property}' from element ID '${elementId}'.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

// Usage example:
// <p id="styledText" style="color: blue;">Hello</p>
// setInlineStyle('styledText', 'color', 'red');
// setInlineStyle('styledText', 'fontSize', '20px'); // CamelCase for CSS properties
// removeInlineStyle('styledText', 'color');
How it works: This snippet illustrates how to directly manipulate an element's inline CSS styles using JavaScript. The `element.style` object allows setting and removing individual CSS properties, offering fine-grained control over an element's visual appearance dynamically. Remember to use camelCase for CSS properties like `fontSize`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs