JavaScript HTML DOM – Changing CSS
14 April 2025 | Category: JavaScript
One of the coolest things you can do with JavaScript is change the style (CSS) of HTML elements dynamically. This lets you build interactive, responsive, and animated web experiences.
🧠 What Does “Changing CSS” Mean?
With JavaScript, you can:
✅ Change the color, font, size, and layout
✅ Add or remove classes
✅ Dynamically toggle styles
✅ Animate elements
All of this is possible through the DOM (Document Object Model).
🔧 1. Changing Inline Styles Using .style
You can directly change CSS properties using the style
property.
✅ Example:
<p id="text">Hello World</p>
<button onclick="changeStyle()">Change Style</button>
<script>
function changeStyle() {
const el = document.getElementById("text");
el.style.color = "blue";
el.style.fontSize = "24px";
el.style.backgroundColor = "lightyellow";
}
</script>
📌 Note: Use camelCase for CSS properties in JS (
backgroundColor
, notbackground-color
).
🧱 2. Adding or Removing CSS Classes
Instead of writing inline styles, it’s cleaner to add/remove classes.
✅ Example:
<style>
.highlight {
background-color: black;
color: white;
padding: 10px;
border-radius: 5px;
}
</style>
<p id="msg">Click to highlight me!</p>
<button onclick="toggleHighlight()">Toggle</button>
<script>
function toggleHighlight() {
const el = document.getElementById("msg");
el.classList.toggle("highlight");
}
</script>
🧠
classList
is a powerful way to manage CSS classes:
.add("className")
.remove("className")
.toggle("className")
.contains("className")
🔁 3. Changing Multiple Styles Dynamically
element.style.cssText = "color: red; background-color: black; font-size: 20px;";
🎨 4. Using CSS Variables with JavaScript
You can control CSS custom properties (variables) from JavaScript too.
<style>
:root {
--main-color: teal;
}
body {
background-color: var(--main-color);
}
</style>
<button onclick="changeTheme()">Change Theme</button>
<script>
function changeTheme() {
document.documentElement.style.setProperty('--main-color', 'salmon');
}
</script>
🧪 Real World Example – Light/Dark Mode
<style>
body {
transition: 0.3s;
background-color: white;
color: black;
}
.dark {
background-color: #121212;
color: white;
}
</style>
<button onclick="toggleTheme()">Toggle Dark Mode</button>
<script>
function toggleTheme() {
document.body.classList.toggle("dark");
}
</script>
🧠 Summary
Task | Method |
---|---|
Change inline CSS | element.style.property = "value" |
Add a class | element.classList.add("className") |
Remove a class | element.classList.remove("className") |
Toggle a class | element.classList.toggle("className") |
Set multiple styles | element.style.cssText = "..." |
Change CSS variables | element.style.setProperty("--var", "value") |
✅ Conclusion
JavaScript lets you control how your webpage looks and behaves in real-time. By changing CSS with JavaScript, you can create stunning effects, animations, themes, and interactive elements that impress users.