You’ve learned the box called a variable. But just putting something in a box doesn’t change the screen. Now, let’s rewrite HTML text from JavaScript and make a visible change happen. This is the first moment where “HTML and JavaScript connect.”
Put a name tag on the place you want to rewrite
First, on the HTML side, put an id (a name tag) on the place you want to say “I want to rewrite here.”
<h1 id="greeting">Hello</h1>id="greeting" is like a nickname you gave this heading. It’s a marker for calling it up from JavaScript as “that one named greeting.”
Catch it, then rewrite it
Relying on that name tag, catch the place with JavaScript and swap its contents.
const el = document.getElementById("greeting");
el.textContent = "Hey there!";Read out loud, it goes like this.
| Line | What it does |
|---|---|
| Line 1 | Catch the place with the name tag greeting, and put it in the box el |
| Line 2 | Rewrite that place’s textContent (the text shown) to “Hey there!” |
With this, the “Hello” on the screen changes to “Hey there!” What you wrote appears as text on the screen—the variable you just learned comes to life here.
Words alone are hard to picture, so see the change for yourself. Press the button below to run the two lines of JavaScript above.
Hello the whole time. The text on the screen swaps anyway.Summary of this lesson
- Put a name tag on the place you want to rewrite, using
id - Catch the place with
getElementById - Put text into
textContent, and the text is rewritten
