How do you manipulate CSS styles using JavaScript?
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 elementconst myDiv = document.getElementById('myDiv');// Change the background colormyDiv.style.backgroundColor = 'blue';// Set multiple stylesmyDiv.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 elementconst myDiv = document.getElementById('myDiv');// Add a classmyDiv.classList.add('newClass');// Remove a classmyDiv.classList.remove('oldClass');// Toggle a classmyDiv.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 variabledocument.documentElement.style.setProperty('--main-color', 'blue');// Get the value of a CSS variableconst 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 elementconst link = document.createElement('link');link.rel = 'stylesheet';link.href = 'styles.css';// Append the link element to the headdocument.head.appendChild(link);// Remove the link elementdocument.head.removeChild(link);