Change CSS with JavaScript Vanilla JS
You can make changes to the CSS styles of elements on your web page when an event occurs using JavaScript. This is how to change CSS with JavaScript.
Change CSS with the style property in JavaScript
If you are changing a single property of an element like background color, you can do so with a single line of JavaScript using the .style
property on that element.
Within .style
, you'll need to specify the property you want to change such as color
or backgroundColor
.
Note that the property backgroundColor is written in camel case rather than hypenated like it is in CSS (background-color). This means that the first word is always written is lower case and if there is a second word there is no space or hypen and the first letter of the second word is capitalized.
When using the element.style.property
to change styles, the styles you add are applied inline within the style=""
attribute on the HTML element. This means they will have higher specificity than styles written in an external stylesheet and overwrite any existing styles unless they are using !important
.
To remove a style from the style=""
attribute with JavaScript, you set the value of the CSS property to null
or an empty string.
// or
document.querySelector('h1').style.backgroundColor = "";
This won't remove styles written in your stylesheets, only those present in the style=""
attribute. You can overwrite styles written in your stylesheet by setting the value of the property to a different value like "orange" but you can't remove the orginal style with this method. To remove a style from an element that was applied by a stylesheet, you can remove the class from the element or remove any other attribute that the original CSS rule targets.
Change CSS by adding or removing a class with JavaScript
If you want to change more than just a couple of style properties, it might be better to simply write those styles in a CSS class and add the class to the element with JavaScript.
You can also remove a class from an element to remove all the styles from that element that are assigned to that class.
Or you may prefer this method simply because it keeps function and presentation more separate.
You can do this with element.classList.add()
and element.classList.remove()
.
document.querySelector('h1').classList.add('new-class');
// remove class
document.querySelector('h1').classList.remove('existing-class');
If you are adding a second class to an element to change the styles, make sure that your CSS rule for the second class is written later in the stylesheet than the first class so it will be able to overwrite the original styles.
For more details on how to select the element that you want to change the styles on, read my article on several ways to get element in vanilla JavaScript.
Thanks for reading.
Ryan
Published on 31 Aug 2022