JavaScript: DOM Styles

🗓 Last updated: 2026-11-30👤 Written by: Blake✓ Reviewed by: Dana🏷 Category: JavaScript Tutorial

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.


Related DOM Methods:element.style classList class

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.

HTML
<!-- 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>
⚠️ Note: CSS property names with hyphens must be converted to camelCase in JS: background-color → backgroundColor, font-size → fontSize. This is one of the most common pitfalls for beginners.

▶ Example: Reading and Writing style Property

▶ Try it Yourself

2. 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.

HTML
<!-- 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>
💡 Tip: Assigning 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 Yourself

3. getComputedStyle

element.style can only read inline styles. How do you read styles defined in CSS files or <style> tags? The answer is getComputedStyle.

HTML
<!-- 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>
💡 Tip: 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 Yourself

4. 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.

HTML
<!-- 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>
⚠️ Note: Assigning to cssText will replace all existing inline styles. To append, use +=: element.style.cssText += '; color: red;'.

▶ Example: cssText Batch Styling

▶ Try it Yourself

Related DOM Methods:element.style classList class

❓ FAQ

Q What is the difference between element.style and getComputedStyle?
A 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.
Q After setting styles with element.style, nothing changed. What could be the reason?
A A common cause is writing the property name in CSS form, for example 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.
Q To change multiple styles at once, should I use cssText or set style one by one?
A For batch setting you can use 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

📝 Exercises

  1. Basic: Create a page with 3 buttons (red/green/blue). When clicked, use style.backgroundColor to change the page background color.
  2. Intermediate: Use classList.toggle to implement a "highlight" feature—click a paragraph to toggle a highlight class (yellow background), click again to remove it.
  3. Challenge: Implement a simple "night mode"—toggle with a button, use getComputedStyle to read the current background color to determine the mode, and display "Current mode: Day/Night" on the page.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏