JavaScript·100 questions

[ITEM 4] QUESTION: How to change element styles?

Answer

Changing element styles using JavaScript allows you to create dynamic and responsive interfaces that react to user actions in real time. There are several approaches to managing the appearance of elements, each suitable for a specific range of tasks.

The most direct way to change an individual style property is to access the style property of the target element, for example: el.style.color = 'red'. It is important to remember that CSS property names consisting of multiple words are written in JavaScript in camelCase format instead of kebab-case. Thus, the CSS property background-color turns into backgroundColor in JavaScript. This approach is ideal for targeted changes to one or two parameters when the logic is encapsulated directly in the script.

If you need to apply multiple styles simultaneously, it is more convenient to use the cssText property. It allows you to write an entire string of CSS rules directly into an element, for example: el.style.cssText = 'color: red; background-color: blue; font-size: 16px;'. However, it is worth considering that assigning a value via cssText completely overwrites all inline styles that were previously set via the style property.

Sometimes there is a need to find out not what is written in the element's inline styles, but its actual styles computed by the browser, taking into account all stylesheets and inheritance rules. For this, the global getComputedStyle(el) function is used. It returns an object with all computed styles of the element, the values of which can be read, but cannot be directly modified through this object.

Working with CSS custom properties (variables) deserves special attention. You can dynamically change the values of CSS variables directly from JavaScript by calling the setProperty method on the element's style object. For example, el.style.setProperty('--main-color', '#ff0000'). This is an incredibly powerful approach for implementing themes, where all appearance logic is moved to CSS, and the script merely switches variable values.

Was this answer helpful?

More questions in this topic

Related questions from other topics