Search⌘ K
AI Features

Modifying CSS

Explore how to modify CSS on HTML elements using JavaScript by working with the Element.style property for individual CSS changes and Element.classList methods for managing classes. Understand how to add, remove, toggle, and replace CSS classes to create dynamic style effects and improve interactivity in your web projects.

The Element.style property

The easiest way to change CSS styles on an HTML element using Javascript is to access individual styles in the Element.style property. Since Element.style is also an object, there are many sub-properties that target specific CSS properties. For instance, we could add a border to an element using Element.style.border:

Implementation of Element.style

We could also change the text alignment with Element.style.textAlign:

Changing text alignment using Element.style.textAlign

There are many, many CSS properties that can be accessed within Element.style. A full list can be found on the Mozilla documentation. Browse through the list to get a sense of the different properties you can target using Javascript.

Exercise

Use Element.style to change the width of the h1 element to half that of its parent container.

Test your learning

Programmatically styling with classes using Element.classList

Although it is perfectly valid to modify styles with Element.style, what if you want to modify multiple CSS properties?

For instance, let’s say we want to highlight an element when we click it by changing both the background-color and color. Using Element.style, the code would look something like this:

Implementation of Element.style

However, a better way to add multiple styles would be to create a class with those CSS properties and then add the class to the HTML element. We can use Element.classList to:

  • Check the class values associated with an element.
  • Add/remove classes toggle class values.
  • Check whether a certain class is associated with an element.
  • Replace one class with another class.

Let’s go back to the previous example. We could highlight the h1 element using Element.classList.add(class):

Implementation of Element.classList.add(class)

We could also toggle the “highlight” behavior using Element.classList.toggle(class):

Implementation of Element.classList.toggle(class)

Additionally, we can use Element.classList.remove(class) to remove a class and Element.classList.contains(class) to check if the element has a certain class value associated with it. To replace one class with another, use Element.classList.replace(oldClass, newClass).

Exercise

Given the following CSS definition:

NAME_
CSS
.invisible {
opacity: 0;
}

Use methods in Element.classList to make the following picture switch between disappearing and reappearing when it is clicked:

Test your learning