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.
<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>
background-color → backgroundColor, font-size → fontSize. This is one of the most common pitfalls for beginners.
Example: Reading and Writing style Property
<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>
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.
<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>
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
<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>
Example: Show and Hide
<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>
getComputedStyle
element.style can only read inline styles. How do you read styles defined in CSS files or <style> tags? The answer is getComputedStyle.
<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
<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>
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.
<div id="box">Batch Styling</div>
<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
<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>
📖 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.
❓ FAQ
element.style.color read the color set in a CSS file?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.classList.toggle conditionally add or remove?classList.toggle('cls', force) takes a second parameter: true forces adding, false forces removing. It's equivalent to force ? add : remove.style or classList to modify styles?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
- 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.



