404 Not Found

404 Not Found


nginx

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.


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
<div id="box">Hello Style</div>
<script>
const element = document.getElementById('box');
element.style.color = 'red';
element.style.fontSize = '20px';  // Note: CSS font-size → JS fontSize
</script>
⚠️ CSS property names with hyphens must be converted to camelCase in JS: background-colorbackgroundColor, font-sizefontSize. This is one of the most common pitfalls for beginners.

Example: Reading and Writing style Property

HTML
<div id="box" style="color: blue;">Hello Style</div>

<script>
const box = document.getElementById('box');

console.log('Current color:', box.style.color);

box.style.color = 'red';
box.style.fontSize = '24px';
box.style.backgroundColor = '#f0f0f0';
box.style.padding = '10px';
box.style.borderRadius = '8px';
</script>
▶ Try it Yourself

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.

className

className is a string, and assigning to it will overwrite all existing classes.

HTML
<div id="demo1" class="item">Element 1</div>
<div id="demo2" class="item">Element 2</div>
<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>
💡 Assigning className is like factory-resetting your phone then installing new apps—everything before is gone. In most cases, classList is safer.

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

HTML
<style>
  .dark { background: #222; color: #fff; }
  .light { background: #fff; color: #222; }
  body { transition: background 0.3s, color 0.3s; padding: 20px; }
</style>

<body class="light">
  <h2>Theme Switching Demo</h2>
  <p>Click the button to toggle between light and dark themes</p>
  <button id="toggleBtn">Switch Theme</button>
</body>

<script>
const body = document.body;
const btn = document.getElementById('toggleBtn');

btn.addEventListener('click', function() {
  body.classList.toggle('dark');
  body.classList.toggle('light');
});
</script>
▶ Try it Yourself

Example: Show and Hide

HTML
<style>
  .hidden { display: none; }
  .panel { border: 1px solid #ccc; padding: 15px; margin-top: 10px; }
</style>

<button id="togglePanel">Show/Hide Panel</button>
<div id="panel" class="panel">This is the panel content</div>

<script>
const panel = document.getElementById('panel');
const btn = document.getElementById('togglePanel');

btn.addEventListener('click', function() {
  panel.classList.toggle('hidden');
  btn.textContent = panel.classList.contains('hidden') ? 'Show Panel' : 'Hide Panel';
});
</script>
▶ Try it Yourself

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
<div id="box">Test Element</div>
<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

HTML
<style>
  #measured { font-size: 18px; color: green; margin: 20px; }
</style>

<div id="measured">Measure my styles</div>

<script>
const el = document.getElementById('measured');

console.log('color from style attribute:', el.style.color);
console.log('color from computed style:', getComputedStyle(el).color);
console.log('fontSize from computed style:', getComputedStyle(el).fontSize);
console.log('margin from computed style:', getComputedStyle(el).margin);
</script>
▶ Try it Yourself

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
<div id="box">Batch Styling</div>
<script>
const element = document.getElementById('box');
element.style.cssText = 'color: red; font-size: 20px; padding: 10px;';
</script>
⚠️ Assigning to cssText will replace all existing inline styles. To append, use +=: element.style.cssText += '; color: red;'.

Example: cssText Batch Styling

HTML
<div id="box">Batch Styling</div>

<script>
const box = document.getElementById('box');
box.style.cssText = 'color: white; background: #4CAF50; padding: 15px; border-radius: 8px; font-size: 18px; text-align: center;';
</script>
▶ Try it Yourself

📖 Summary

  1. element.style only operates on inline styles; it cannot read rules from CSS files. Property names must use camelCase when writing.
  2. className assignment overwrites all classes. Using classList with add/remove/toggle is safer.
  3. getComputedStyle reads the element's final computed style; the return value is read-only.
  4. cssText batch-sets inline styles, but assignment replaces existing inline styles.

❓ FAQ

Q Why can't element.style.color read the color set in a CSS file?
A The style property only corresponds to inline style="...". Rules from CSS files and <style> tags are outside its scope. Use getComputedStyle(element).color to read the final value.
Q Can classList.toggle conditionally add or remove?
A Yes. classList.toggle('cls', force) takes a second parameter: true forces adding, false forces removing. It's equivalent to force ? add : remove.
Q Should I use style or classList to modify styles?
A The rule is simple: use style for one-off temporary style changes, use classList with CSS classes for state/theme switching. The latter keeps styles in CSS and logic in JS, making maintenance easier.

📝 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.
100%

🙏 帮我们做得更好

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

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