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:

Inline styles changed with `Element.style.cssProperty`
Inline styles changed with `Element.style.cssProperty`

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:

  1. Change the button’s color
  2. Change the button’s backgroundColor
  3. Change the button’s width
  4. Change the button’s height

Answers

  • Create a button.
<button> Click me! </button>
  • Do the following when the button is clicked:
  1. Change the button’s color
  2. Change the button’s backgroundColor
  3. Change the button’s width
  4. Change the button’s height
const button = document.querySelector('button')
button.addEventListener('click', event => {
  button.style.color = 'blue'
  button.style.backgroundColor = 'orangered'
  button.style.width = '500px'
  button.style.height = '3em'
})