Changing CSS with JavaScript
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Changing CSS with JavaScript
Sometimes, you need to set your element’s CSS with JavaScript. To do so, you can use the style
property.
Setting CSS
You can assign a new value to the CSS property you want to change. Here’s the syntax.
// Setting the property
// NOTE: Change 'cssProperty' to any CSS Property, written in camelCase.
Element.style.cssProperty = propertyValue
You can change any CSS Property. Here are some examples:
const element = document.querySelector('.element')
element.style.color = 'red'
element.style.backgroundColor = 'blue'
element.style.fontSize = '2em'
element.style.fontWeight = '700'
Once you run this code, you should see the applied inline style if you open up the Elements tab in your console:
Another way to set CSS
You can also change CSS with the setProperty
method. This method takes in two values—the property you want to set, and the value it should take up.
element.style.setProperty('color', 'red')
This method can be used to set custom CSS properties
element.style.setProperty('--theme-color', 'orange')
Exercise
Create a button. Do the following when the button is clicked:
- Change the button’s color
- Change the button’s backgroundColor
- Change the button’s width
- Change the button’s height