HTML Code

JS Styles

Manipulating CSS Styles with JavaScript 

JavaScript allows you to change, add, and remove styles dynamically using the .style property, classList, and CSS stylesheets.

Changing Styles with .style

You can directly modify an element’s style using .style.property.

Example: Change Background Color

<p id=”myPara”>This is a paragraph.</p>
<button onclick=”changeStyle()”>Change Style</button>

<script>
function changeStyle() {
document.getElementById(“myPara”).style.color = “red”;
document.getElementById(“myPara”).style.fontSize = “20px”;
document.getElementById(“myPara”).style.backgroundColor = “yellow”;
}
</script>

This is a paragraph.

Adding & Removing CSS Classes

Instead of modifying individual styles, use classList to apply predefined CSS classes.

Example: Toggle Dark Mode

<style>
.dark-mode {
background-color: black;
color: white;
padding: 10px;
}
</style>

<p id=”para”>Click the button to toggle dark mode.</p>
<button onclick=”toggleMode()”>Toggle Dark Mode</button>

<script>
function toggleMode() {
document.getElementById(“para”).classList.toggle(“dark-mode”);
}
</script>

Click the button to toggle dark mode.

Changing Multiple Elements’ Styles

Use querySelectorAll() to style multiple elements at once.

Example: Change All Paragraphs’ Colors

<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<button onclick=”changeAll()”>Change All Colors</button>

<script>
function changeAll() {
document.querySelectorAll(“p”).forEach(p => p.style.color = “blue”);
}
</script>

Paragraph 1

Paragraph 2

Paragraph 3

Changing Styles from External CSS

Modify an external CSS rule dynamically.

Example: Change CSS Variable (Custom Property)

<style>
:root {
–main-color: blue;
}
p {
color: var(–main-color);
}
</style>

<p>This paragraph uses a CSS variable.</p>
<button onclick=”changeCSS()”>Change Variable</button>

<script>
function changeCSS() {
document.documentElement.style.setProperty(“–main-color”, “red”);
}
</script>

This paragraph uses a CSS variable.

Reset Styles

You can remove inline styles using .style.removeProperty().

Example: Reset Styles

<p id=”resetPara” style=”color: red; font-size: 20px;”>Styled text</p>
<button onclick=”resetStyle()”>Reset Style</button>

<script>
function resetStyle() {
document.getElementById(“resetPara”).style.removeProperty(“color”);
document.getElementById(“resetPara”).style.removeProperty(“font-size”);
}
</script>

Styled text

Scroll to Top