Changing Styles

How a page looks (colors, sizes, fonts) is described by CSS. A CSS rule has a selector, which says which elements the rule applies to, and then in curly braces how they should look:

h1 {
    color: purple;
    background-color: yellow;
}

This rule makes the main heading purple on a yellow background. color and background-color are CSS properties, purple and yellow their values. A page can have its CSS in the style element in head; you'll find one in this exercise's index.html.

JavaScript can change the look of an element through its property style:

const heading = document.querySelector("h1");
heading.style.color = "purple";
heading.style.fontSize = "48px";

The values are text in quotes, written the same way as in CSS. CSS property names with a hyphen are written in camelCase in JavaScript: background-color becomes backgroundColor, font-size becomes fontSize. That's because a hyphen in JavaScript means minus: JavaScript would read heading.style.background-color = "yellow"; as the subtraction heading.style.background - color, and you can't assign a value to a subtraction. None of the script would run, and the console would show SyntaxError: Invalid left-hand side in assignment.

Setting styles one by one gets long. More often, the look is prepared in the page's CSS as a class, and JavaScript only adds the class to an element or removes it. For example, the page in this exercise has a list (ul, with an li element for each item) and this CSS rule for elements with the class done:

.done {
    color: gray;
    text-decoration: line-through;
}

Every element has the property classList with these methods:

  • classList.add("done") adds the class done to the element,
  • classList.remove("done") removes it,
  • classList.toggle("done") adds it if the element doesn't have it, and removes it if it does. That's handy for buttons, as you'll see in the next exercise.

Write the class name without the dot: add("done"), not add(".done"). The dot belongs only in selectors. With it, you'd add a class called .done, which no CSS rule matches, so nothing would change.

Instructions

Make the heading teal: set its style.color to "teal".

Give the heading a light yellow background: set the CSS property background-color to "lightyellow". Remember to use camelCase.

The shopping is done: add the class done to shopping. But the homework isn't finished after all: remove the class done from homework.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/10