BETAThis is a new service – your feedback will help us to improve it.

Affecting the page

All our programs so far have just printed their results out to the console, but Javascript on real websites needs to do more than that.

Javascript is often used to show or hide parts of a page based on user actions. We often do this by adding and removing classes.

Create a new, empty Codepen and follow along, inserting the HTML, CSS and JS into the right panels.

Let's say we have some HTML on our page:

<h1>My text here</h1>

And in our CSS, we have a class defined like this:

.red-text{
  color: red;
}

We can use javascript to apply the red-text class to our HTML based on how the user interacts with the page.

Selecting page elements

We can select HTML elements on our webpage and save them as variables like this:

const heading = document.querySelector("h1")

We can write any ID, class or element name inside document.querySelector(""), just like in CSS.

You may see this referred to as selecting DOM elements.

Adding and removing classes

Once we've selected the right HTML and saved it as a variable, we can add a class to it like this:

const heading = document.querySelector("h1")

heading.classList.add('red-text')

When this code runs, the text should turn red.

We could also remove a class that already exists with:

heading.classList.remove('red-text')

Next, we'll look at how to trigger these changes based on things the user does.

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Adding interactivity
  1. Introducing Javascript
  2. Your first Javascript program
  3. Variables
  4. Conditional logic
  5. Affecting the page
  6. Making a menu
  7. Responding to user actions
  8. Keep your Javascript accessible
  9. Get confident with Javascript
  10. Add interactivity to your prototypesP