Script Valley
JavaScript in the Browser: DOM, Events & APIs
Styles, Classes, and Layout via JavaScriptLesson 3.2

Reading and setting inline styles with element.style

element.style object, camelCase properties, getComputedStyle, CSS custom properties, style.cssText, when to use inline styles

Inline Styles with element.style

element.style reads and writes only the element's inline style attribute. CSS properties become camelCase properties on the object.

const box = document.querySelector('.box');
box.style.backgroundColor = '#f0f0f0';
box.style.width = '200px';
box.style.transform = 'translateX(50px)';

getComputedStyle โ€” Reading Actual Applied Styles

element.style.color returns empty string if the color was set by a stylesheet. Use getComputedStyle to read the final calculated value.

const styles = getComputedStyle(box);
console.log(styles.color);       // 'rgb(0, 0, 0)'
console.log(styles.fontSize);    // '16px'

CSS Custom Properties

// Set a CSS variable on an element
box.style.setProperty('--accent', '#e74c3c');
const accent = getComputedStyle(box).getPropertyValue('--accent');

When to Use Inline Styles

Use element.style for dynamic values that cannot be pre-written in CSS โ€” animation progress values, user-dragged positions, chart bar heights. For state changes (open/closed, active/inactive), always prefer toggling a class.

Up next

How to read element dimensions and position in the browser

Sign in to track progress

Reading and setting inline styles with element.style โ€” Styles, Classes, and Layout via JavaScript โ€” JavaScript in the Browser: DOM, Events & APIs โ€” Script Valley โ€” Script Valley