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 290 Frontend lessons + 1,000+ 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.