JavaScript Notes
Learn to dynamically change CSS styles with JavaScript. Master inline styles, classList, getComputedStyle, CSS variables, dark mode toggle, and animations with practical examples and performance tips.
Two Approaches: Inline Styles vs CSS Classes
You have two main ways to change element appearance with JavaScript. Knowing when to use each is key:
Setting Multiple Styles with cssText
const card = document.getElementById('card');
// Set multiple styles at once — replaces ALL existing inline styles
card.style.cssText = `
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 16px;
font-size: 20px;
box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
`;
// ⚠️ WARNING: cssText REPLACES everything — previous inline styles gone!
console.log(card.style.cssText); // shows new styles only
// To ADD without replacing existing:
card.style.cssText += 'border: 2px solid white;';getComputedStyle() — Read the ACTUAL Applied Style
The style property only reads inline styles (set directly on the element). To get the actual computed value — including styles from CSS files, <style> tags, or browser defaults — use getComputedStyle().
<style>
.card {
width: 300px;
padding: 20px;
background-color: #2196F3;
font-size: 16px;
}
</style>
<div class="card" id="myCard" style="color: red;">Hello Card</div>
<script>
const card = document.getElementById('myCard');
// style property — only reads INLINE styles
console.log(card.style.width); // "" (not set inline)
console.log(card.style.backgroundColor); // "" (comes from class)
console.log(card.style.color); // "red" (set inline ✓)
// getComputedStyle — reads ACTUAL rendered values
const computed = getComputedStyle(card);
console.log(computed.width); // "300px"
console.log(computed.padding); // "20px"
console.log(computed.backgroundColor); // "rgb(33, 150, 243)"
console.log(computed.fontSize); // "16px"
console.log(computed.color); // "rgb(255, 0, 0)" (red)
console.log(computed.display); // "block"
// Useful for calculations
const width = parseInt(computed.width); // 300
const padding = parseInt(computed.padding); // 20
console.log(`Content + padding: ${width + padding * 2}px`); // "340px"
</script>"" "" "red" "300px" "20px" "rgb(33, 150, 243)" "16px" "rgb(255, 0, 0)" "block" "Content + padding: 340px"
classList — The Recommended Way to Change Styles
Instead of writing CSS values in JavaScript, define classes in CSS and toggle them with classList. This keeps CSS in CSS files and JS in JS files.
"btn active" "btn" true false true true false ["btn", "active"]
CSS Variables (Custom Properties) via JavaScript
CSS variables defined with -- can be read and changed from JavaScript using setProperty and getPropertyValue.
<style>
:root {
--primary-color: #007bff;
--font-size-base: 16px;
--spacing: 20px;
}
.themed-card {
background: var(--primary-color);
font-size: var(--font-size-base);
padding: var(--spacing);
}
</style>
<div class="themed-card" id="card">Themed Card</div>
<button onclick="changeTheme()">Change Theme</button>
<script>
function changeTheme() {
const root = document.documentElement; // :root element
// Reading CSS variables
const primary = getComputedStyle(root).getPropertyValue('--primary-color');
console.log(primary.trim()); // "#007bff"
// Changing CSS variables — affects ALL elements using var(--primary-color)!
root.style.setProperty('--primary-color', '#e74c3c');
root.style.setProperty('--font-size-base', '18px');
root.style.setProperty('--spacing', '30px');
console.log('Theme updated!');
}
</script>"#007bff" "Theme updated!"
Power of CSS variables: Changing one variable updates every element that uses it. This is how theme switching and dark mode work efficiently.
Real World Use Case: Dark Mode Toggle
Common Mistakes
❌ Mistake 1: Using kebab-case for style property names
❌ Mistake 2: Reading style property from stylesheet (not inline)
// CSS has: .card { width: 300px; }
const card = document.querySelector('.card');
// ❌ Returns empty string — style only reads INLINE styles
console.log(card.style.width); // ""
// ✅ Use getComputedStyle for stylesheet values
console.log(getComputedStyle(card).width); // "300px"❌ Mistake 3: Forgetting units when setting styles
// ❌ No unit — silently fails in most browsers
box.style.width = 200; // ignored!
box.style.fontSize = 16; // ignored!
// ✅ Always include units
box.style.width = '200px';
box.style.fontSize = '16px';
// Exception: unitless properties like zIndex, opacity
box.style.zIndex = 10; // OK — zIndex has no unit
box.style.opacity = 0.5; // OK — opacity is 0-1❌ Mistake 4: Inline styles vs classList (maintainability)
// ❌ Hard to maintain — CSS logic scattered in JS files
btn.style.backgroundColor = 'blue';
btn.style.color = 'white';
btn.style.padding = '10px 20px';
btn.style.borderRadius = '5px';
// ✅ Better — define class in CSS, just toggle in JS
// CSS: .btn-active { background: blue; color: white; ... }
btn.classList.add('btn-active');Interview Questions
Q1. What is the difference between element.style.property and getComputedStyle(element).property? > element.style.property reads only inline styles (set directly via style attribute or JS). getComputedStyle() returns the final computed value considering all stylesheets, inheritance, and cascade. For most elements, element.style.color will be empty unless you set it inline.
Q2. Why should you prefer classList.toggle() over directly setting style properties? > Using classList keeps CSS in stylesheets (separation of concerns), makes code more maintainable, allows CSS transitions to work properly, and is cleaner to read. Inline styles have the highest CSS specificity and are hard to override later.
Q3. How do you read a CSS custom property (variable) with JavaScript? > Use getComputedStyle(element).getPropertyValue('--variable-name'). To set it: element.style.setProperty('--variable-name', 'value'). Setting on :root (document.documentElement) affects the entire page.
Q4. What is the cssText property and what is its risk? > cssText lets you set multiple inline styles at once as a CSS string. The risk is it replaces all existing inline styles entirely. Use it when you want to set all styles from scratch; use individual property assignment to add/change one style.
Q5. How do you remove an inline style using JavaScript? > Set the property to an empty string: element.style.backgroundColor = ''. This removes that specific inline style, allowing the stylesheet rule to take effect again. Alternatively, use element.style.removeProperty('background-color').
Q6. Why must CSS property names be camelCase in JavaScript? > Hyphens in property names would be interpreted as the subtraction operator. So CSS background-color becomes JS backgroundColor, border-radius becomes borderRadius, etc. The special exception is float which becomes cssFloat.
Key Takeaways
✅ Use camelCase for style properties: fontSize not font-size
✅ element.style only reads/writes INLINE styles
✅ getComputedStyle() reads the actual applied value from ALL CSS sources
✅ classList.add/remove/toggle is preferred over inline styles
✅ Always include units: '200px', '1.5rem', '50%'
✅ CSS variables can be changed via JS — powerful for theming
✅ cssText replaces ALL inline styles — use carefully
✅ Remove an inline style by setting it to empty string: style.color = ''Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript DOM Changing Styles - CSS Manipulation, classList & getComputedStyle.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, dom, changing, styles
Related JavaScript Master Course Topics