learn2kode.in

JavaScript Changing Styles (DOM Style Manipulation)

JavaScript allows you to change the appearance of HTML elements dynamically using the DOM. This is called style manipulation. It is commonly used to create interactive effects like highlighting elements, showing or hiding content, changing themes, and responding to user actions.
Changing styles with JavaScript is a core skill for building modern, interactive websites.

Why Change Styles Using JavaScript?

Using JavaScript to change styles helps you:
Accessing the style Property
Every HTML element has a style property that lets you apply inline CSS styles.
Example
<div id="box">Hello World</div>
const box = document.getElementById("box");

box.style.color = "white";
box.style.backgroundColor = "blue";
box.style.padding = "20px";
CSS properties written with hyphens become camelCase in JavaScript.
CSS Property JavaScript Property
background-color backgroundColor
font-size fontSize
border-radius borderRadius
text-align textAlign
Changing Multiple Styles
You can update multiple styles one by one:
const heading = document.querySelector("h1");

heading.style.fontSize = "32px";
heading.style.color = "green";
heading.style.textAlign = "center";
Showing and Hiding Elements
JavaScript is often used to control visibility.
// Hide element
element.style.display = "none";

// Show element
element.style.display = "block";
Other useful properties:
Changing Styles on User Events
Styles are commonly changed when users interact with elements.
const btn = document.getElementById("btn");

btn.addEventListener("click", function () {
  btn.style.backgroundColor = "orange";
  btn.style.color = "white";
});
Using classList (Best Practice)
Instead of adding inline styles, it’s better to toggle CSS classes.
JavaScript
const box = document.getElementById("box");
box.classList.add("active");
box.classList.remove("active");
box.classList.toggle("active");
CSS
.active {
  background-color: teal;
  color: white;
  transform: scale(1.1);
}
Changing Styles for Multiple Elements
const items = document.querySelectorAll(".item");

items.forEach(item => {
  item.style.border = "2px solid #333";
});
Inline Styles vs Class-Based Styles (Comparison)
Method Inline Styles CSS Classes
Maintainability Low High
Performance Lower Better
Best Practice ❌ Avoid ✔ Recommended
Best Practices