JAVASCRIPT

Dynamically Apply Inline CSS Styles to an Element

Programmatically change multiple CSS properties of a single DOM element's inline style using JavaScript's `element.style` property for direct visual adjustments and animations.

// Assume an HTML element: <div id="styledBox" style="width: 100px; height: 100px; background-color: lightgray;"></div>
const styledBox = document.getElementById('styledBox');

if (styledBox) {
    console.log('Initial styles:', styledBox.style.cssText);

    // 1. Set individual style properties
    styledBox.style.backgroundColor = 'purple'; // camelCase for CSS properties
    styledBox.style.color = 'white';
    styledBox.style.padding = '15px';

    // 2. Set multiple styles at once using cssText (overwrites existing inline styles)
    // Be cautious: this overwrites *all* existing inline styles.
    // styledBox.style.cssText = 'background-color: navy; color: yellow; border: 2px solid orange;';

    // More controlled way to add multiple without overwriting (but might be less efficient for many properties)
    Object.assign(styledBox.style, {
        border: '2px solid red',
        borderRadius: '8px',
        fontSize: '1.2em'
    });

    console.log('Updated styles (individual):', styledBox.style.cssText);

    // 3. Get a specific inline style property
    const currentBgColor = styledBox.style.backgroundColor;
    console.log('Current background color:', currentBgColor); // Output: purple

    // 4. Remove an inline style property
    styledBox.style.padding = ''; // Setting to an empty string removes the inline style
    console.log('Styles after padding removal:', styledBox.style.cssText);
} else {
    console.error("Element with id 'styledBox' not found.");
}
How it works: The `element.style` property allows direct manipulation of an element's inline CSS styles. You can set individual properties using camelCase names (e.g., `backgroundColor` for `background-color`). `cssText` can be used to set or retrieve all inline styles as a string, though caution is advised when setting, as it overwrites existing inline styles. Setting a style property to an empty string (`''`) removes that specific inline style. This method is ideal for dynamic, property-specific style changes, especially for animations or real-time UI adjustments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs