Interacting with HTML
- Declare variables that store HTML elements
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:
- Add an ID to the
h1element in the HTML
.getElementByIdto 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 Puppy Facts CodePen starter. 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 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
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?
- What does
- What might
"Front End Workshop"look familiar?
- What does
Try It: Changing Text of an Element
h1 and three
paragraph elements you have variables for.
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