Interacting with HTML

Back to Curriculum Index

Goals

  • Declare variables that store HTML elements
  • Change the content inside an HTML element with JavaScript

Accessing an Element

Variables can also represent parts of the HTML that we’ve written. For example, if we wanted a variable to represent the h1 heading at the top of our page, we’d need to do two things:

  1. Add an ID to the h1 element in the HTML
  2. Use the JavaScript method .getElementById to access that element

Here’s how that looks in practice:

<h1 id="greeting">Hello, world!</h1>
var greetingMessage = document.getElementById('greeting');

console.log(greetingMessage);
// "<h1 id="greeting">Hello, world!</h1>" will print out to the console

Try It: Accessing HTML Elements

Fork this Puppy Facts CodePen starter. Declare four variables, each storing one of the four text-based HTML elements already written. You can decide the variable names to use! In order to access each element, you'll need a unique way to identify each one.

Print each variable out to the console to verify your syntax is correct.

Keep this pen open in a tab; we'll come back to it in the next section!

Need to see an example of this completed? Here you go!

Changing Text of an Element

Accessing elements alone isn’t that cool, but it gets more exciting when we use JavaScript to interact with those HTML elements that we’ve saved to variables. Let’s look at this example:

See the Pen Changing Text of an Element Example by Try Coding (@turing-trycoding) on CodePen.

Before we talk through it, take a minute to sit in that productive struggle and try to sort through what this code is doing, and how. The guiding questions below will help you, if you need them!

  • What is the content inside of each of the <li> tags in the HTML file?
  • What content is showing up in the browser for each of the bullet points?
  • On line 4 of the code:
    • What does firstListItem reference?
    • What might .innerText be doing?
    • Does "Front End Workshop" look familiar?

Try It: Changing Text of an Element

Back in your Puppy Facts CodePen, write JavaScript that will change the content of all four text-based HTML elements you created variables for earlier.

When you've completed this, you should see a different title and set of facts in your browser!

Here's a CodePen you can start with if you closed yours or didn't get it done.

🌶 Click here for a Spicy Challenge 🌶

Do some research to figure out how you can change the src attribute of an img tag in JavaScript! Then, update your image with one that goes with your new facts!


Back to Curriculum Index