Skip to main content
Frontend is a free bonus on CodeMentor AI — the main product is Python. Register to save your progress and unlock all 299 Frontend lessons + 1,100+ Python lessons.Sign up — free
JavaScript & the browser·Module C2 · Lesson 1
TaskHTML has <h1 id='out'>before</h1>. In <script>, query #out and set its textContent to 'after'. Log the textContent as confirmation.

getElementById + textContent: the cheapest DOM update

75 XP6 minFREE
Theory

The simplest DOM call

const el = document.getElementById("greeting");
el.textContent = "Hello, Anna";

getElementById returns the element with the matching id attribute, or null. It's the cheapest selector — no parsing, no CSS engine — so use it when the element has a stable id you control.

textContent vs innerHTML vs innerText

el.textContent = "<b>hi</b>";  // renders literal text "<b>hi</b>"
el.innerHTML   = "<b>hi</b>";  // renders bold "hi" — and runs any <script> tags inside
el.innerText   = "<b>hi</b>";  // similar to textContent, but respects CSS visibility

Use `textContent` by default. It's faster (no HTML parse), safer (no XSS), and works in any context. You only reach for innerHTML when you genuinely need to insert HTML you constructed yourself.

Two trade-offs to know

  1. getElementById returns null if not found — no exception. el.textContent = ... on null then throws. In production code: guard with if (el) or use ?..
  2. The lookup walks the document. For repeated access, cache the reference in a variable instead of calling getElementById in a loop.
2 tabs
Live preview
console output appears here…
PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.