Apply Today to our Software Engineering Program & check out our scholarships!

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:

<!-- HTML code -->
<h1 id="greeting">Hello, world!</h1>
// JS code
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 starter replit. Declare three variables, each storing one of the three paragraph elements already written in HTML. You can decide the variable names to use! In order to access each element, you'll need a unique way to identify each one. This has already been done with the h1 element; you can use that as an example.

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

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

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.

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 <a> tags in the HTML file?
  • What content is showing up in the browser for each of the bullet points?
  • On line 4 of the JavaScript file:
    • What does firstLink reference?
    • What might .innerText be doing?
    • Does "Front End Workshop" look familiar?

Try It: Changing Text of an Element

Back in your Puppy Facts replit, write JavaScript that will change the content of the h1 and three paragraph elements you have variables for, so that your page is about a completely different animal!

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

🌶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!


Optional Extension: Event Listeners
Next: Wrap Up