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 = propertyValueYou 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
Create a button.
<button>Click me!</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
const button = document.querySelector('button')button.addEventListener('click', evt => { button.style.color = 'blue' button.style.backgroundColor = 'orangered' button.width = '500px' button.height = '3em'})Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson