In JavaScript, you interact with an element’s inline styles through the style property. This property represents the style attribute of the HTML element and allows you to read or modify CSS properties directly.

1. Setting Inline Styles

To set a style, you access the style object and then the specific CSS property.

CamelCase Requirement

Because the dot notation in JavaScript doesn’t allow hyphens (like background-color), you must use camelCase for CSS properties.

JavaScript

const box = document.querySelector('.box');

// Setting individual properties
box.style.backgroundColor = 'blue';
box.style.marginTop = '20px';
box.style.borderRadius = '50%';

Setting Multiple Styles at Once

If you want to set a string of CSS all at once (overwriting existing inline styles), use style.cssText.

JavaScript

box.style.cssText = "color: white; padding: 10px; border: 1px solid black;";

2. Getting Inline Styles

You can read values directly from the style object, but there is a major catch: it only reads styles defined inline.

JavaScript

// HTML: <div id="myDiv" style="color: red;"></div>

const myDiv = document.getElementById('myDiv');
console.log(myDiv.style.color); // "red"
console.log(myDiv.style.marginTop); // "" (Empty string if not defined inline)

3. Getting the “Live” Style (getComputedStyle)

If a style is defined in an external CSS file or a <style> block, element.style will return an empty string. To get the actual value currently being applied by the browser, use window.getComputedStyle().

JavaScript

const element = document.querySelector('.sidebar');
const styles = window.getComputedStyle(element);

console.log(styles.width); // Returns the actual width (e.g., "250px")
console.log(styles.getPropertyValue('background-color')); // Alternative syntax

4. Removing Inline Styles

To remove a specific inline style and let the CSS file take over again, set the property to an empty string or use removeProperty.

JavaScript

// Method 1: Set to empty string
box.style.display = '';

// Method 2: removeProperty (uses original CSS naming)
box.style.removeProperty('background-color');

5. Best Practices and Performance

Class Management vs. Inline Styles

In general, it is better for performance and maintainability to toggle CSS classes rather than manipulating inline styles directly. Inline styles have the highest specificity and can be difficult to override later.

JavaScript

// ❌ Potentially messy
el.style.display = 'none';

// ✅ Better approach
el.classList.add('hidden');

Measuring Layout

When reading styles to perform calculations (like an element’s height), computed styles are more reliable. However, for physical dimensions, properties like offsetWidth and offsetHeight are faster and more accurate than parsing strings from getComputedStyle.

Categorized in:

JS DOM,