JavaScript: DOM Styles
After learning how to change page content and structure with JS, the next step is controlling styles—making elements change color, show/hide, or switch themes. CSS handles static styles, JS handles dynamic styles, and together they enable interactivity.
1. style Property
element.style corresponds to the HTML inline style (style="..."). It can only read/write inline styles—it cannot access rules defined in CSS files or <style> tags.
<!-- Container element -->
<div id="box">Hello Style</div>
<!-- Script tag -->
<script>
const element = document.getElementById('box');
element.style.color = 'red';
element.style.fontSize = '20px'; // Note: CSS font-size → JS fontSize
</script>
background-color → backgroundColor, font-size → fontSize. This is one of the most common pitfalls for beginners.
▶ Example: Reading and Writing style Property
▶ Try it Yourself2. className and classList
Manipulating an element's class is the most common way to change styles with JS—you pre-define classes in CSS, then JS just adds or removes class names.
(1) className
className is a string, and assigning to it will overwrite all existing classes.
<!-- Container element -->
<div id="demo1" class="item">Element 1</div>
<!-- Container element -->
<div id="demo2" class="item">Element 2</div>
<!-- Script tag -->
<script>
const el1 = document.getElementById('demo1');
el1.className = 'active'; // Overwrites, only 'active' remains
const el2 = document.getElementById('demo2');
el2.className += ' highlight'; // Appends, but primitive and error-prone
console.log('el1.className:', el1.className);
console.log('el2.className:', el2.className);
</script>
className is like factory-resetting your phone then installing new apps—everything before is gone. In most cases, classList is safer.
(2) classList
classList is a DOMTokenList object that provides methods for adding, removing, and toggling classes without affecting other classes.
| Method | Description |
|---|---|
add('cls') |
Add class |
remove('cls') |
Remove class |
toggle('cls') |
Remove if present, add if absent |
contains('cls') |
Check if class exists, returns boolean |
▶ Example: Theme Switching
▶ Try it Yourself▶ Example: Show and Hide
▶ Try it Yourself3. getComputedStyle
element.style can only read inline styles. How do you read styles defined in CSS files or <style> tags? The answer is getComputedStyle.
<!-- Container element -->
<div id="box">Test Element</div>
<!-- Script tag -->
<script>
const element = document.getElementById('box');
const style = window.getComputedStyle(element);
console.log(style.color); // "rgb(0, 0, 0)"
console.log(style.fontSize); // "16px"
</script>
getComputedStyle returns the element's final computed style—the result of the browser merging all CSS sources (inline, style tags, CSS files, inheritance). The return value is read-only.
▶ Example: Getting Computed Styles
▶ Try it Yourself4. cssText Batch Styling
If you need to set multiple inline styles on an element at once, writing style.xxx = ... line by line is verbose. cssText lets you write them all at once.
<!-- Container element -->
<div id="box">Batch Styling</div>
<!-- Script tag -->
<script>
const element = document.getElementById('box');
element.style.cssText = 'color: red; font-size: 20px; padding: 10px;';
</script>
cssText will replace all existing inline styles. To append, use +=: element.style.cssText += '; color: red;'.
▶ Example: cssText Batch Styling
▶ Try it Yourself❓ FAQ
element.style and getComputedStyle?element.style only reads and writes the element's inline style attribute, so it cannot see rules from CSS files or <style> blocks; getComputedStyle(element) returns the browser's final computed style, including the cascade result. Use the latter to read the styles actually in effect, and use the former or classList to change styles.element.style, nothing changed. What could be the reason?style.background-color will throw an error, so in JS you need to write it in camelCase as style.backgroundColor. Also, style only affects the current element, and if it is overridden by a higher-priority !important rule it will not show, so you can use getComputedStyle to confirm the final value.cssText or set style one by one?element.style.cssText = 'color:red;font-size:14px', which overwrites all inline styles in one assignment, but note that it clears the original inline styles. If you are only changing one or two properties, writing style.xxx one by one is safer; to switch a whole set of appearances, prefer classList together with CSS classes.📖 Summary
element.styleonly operates on inline styles; it cannot read rules from CSS files. Property names must use camelCase when writing.classNameassignment overwrites all classes. UsingclassListwithadd/remove/toggleis safer.getComputedStylereads the element's final computed style; the return value is read-only.cssTextbatch-sets inline styles, but assignment replaces existing inline styles.
📝 Exercises
- Basic: Create a page with 3 buttons (red/green/blue). When clicked, use
style.backgroundColorto change the page background color. - Intermediate: Use
classList.toggleto implement a "highlight" feature—click a paragraph to toggle a highlight class (yellow background), click again to remove it. - Challenge: Implement a simple "night mode"—toggle with a button, use
getComputedStyleto read the current background color to determine the mode, and display "Current mode: Day/Night" on the page.