Change Style with JavaScript Summary

JavaScript can change how an HTML element looks after the page loads. It can change colors, sizes, spacing, borders, and other CSS styles without loading a new page.

CSS gives a webpage its original appearance. JavaScript can then change one of those styles when something happens, such as a person clicking a button or choosing an option.

How to Change a Style with JavaScript

First, the HTML needs an element for JavaScript to find. This paragraph has an ID attribute named message.

<p id="message">This paragraph has a background color.</p>

JavaScript can give that paragraph a light blue background with one line:

document.querySelector('#message').style.backgroundColor = 'lightblue';

When this code runs, the paragraph keeps the same text, but its background color changes.

Find the HTML Element

The first part of the line finds the element that JavaScript will change:

document.querySelector('#message')

document means the current webpage. querySelector() searches that page using a CSS selector. The #message selector finds the element with id="message".

Change the CSS Style

The second part chooses the style and gives it a new value:

.style.backgroundColor = 'lightblue';

style lets JavaScript change the element’s CSS. backgroundColor is the JavaScript version of the CSS property background-color. The equals sign gives that property the new value lightblue.

CSS properties that contain a hyphen are written without the hyphen in JavaScript. The word after the hyphen begins with a capital letter:

  • background-color becomes backgroundColor.
  • font-size becomes fontSize.
  • border-color becomes borderColor.

When Websites Change Styles

Websites change styles to give people visual feedback. A selected option might change color, an error message might turn red, or part of a page might become larger so it is easier to notice.

This example changes a style immediately. In later lessons, you will learn how to change styles after someone clicks a button or changes an input.

Try a Different Style

In the sandbox, replace lightblue with another color such as yellow, pink, or orange. Then select Update Code to see the new background.

You can also replace backgroundColor with color to change the text color instead. Change one part at a time so you can see what each part controls.

Interactive Demo

This element has a new background color.

Code Sandbox

AI Tutor