Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

How do you manipulate CSS styles using JavaScript?

Topics
JAVASCRIPTCSS
Edit on GitHub

TL;DR

You can manipulate CSS styles using JavaScript by accessing the style property of an HTML element. For example, to change the background color of a div element with the id myDiv, you can use:

document.getElementById('myDiv').style.backgroundColor = 'blue';

You can also add, remove, or toggle CSS classes using the classList property:

document.getElementById('myDiv').classList.add('newClass');
document.getElementById('myDiv').classList.remove('oldClass');
document.getElementById('myDiv').classList.toggle('toggleClass');

Manipulating CSS styles using JavaScript

Accessing and modifying inline styles

You can directly manipulate the inline styles of an HTML element using the style property. This property allows you to set individual CSS properties.

// Select the element
const myDiv = document.getElementById('myDiv');
// Change the background color
myDiv.style.backgroundColor = 'blue';
// Set multiple styles
myDiv.style.width = '100px';
myDiv.style.height = '100px';
myDiv.style.border = '1px solid black';

Using the classList property

The classList property provides methods to add, remove, and toggle CSS classes on an element. This is useful for applying predefined styles from your CSS files.

// Select the element
const myDiv = document.getElementById('myDiv');
// Add a class
myDiv.classList.add('newClass');
// Remove a class
myDiv.classList.remove('oldClass');
// Toggle a class
myDiv.classList.toggle('toggleClass');

Modifying styles using CSS variables

CSS variables (custom properties) can be manipulated using JavaScript. This is particularly useful for theming and dynamic styling.

// Set a CSS variable
document.documentElement.style.setProperty('--main-color', 'blue');
// Get the value of a CSS variable
const mainColor = getComputedStyle(document.documentElement).getPropertyValue(
'--main-color',
);
console.log(mainColor);

Using external stylesheets

You can also manipulate styles by dynamically adding or removing stylesheets.

// Create a new link element
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'styles.css';
// Append the link element to the head
document.head.appendChild(link);
// Remove the link element
document.head.removeChild(link);

Further reading

Edit on GitHub