CodeBlanks Logo Icon CodeBlanks

getElementById

JavaScript course · Intermediate · Lesson 20/134

Learn to select an element by id and write safely against a null return.

Selecting an element with getElementById

In HTML we give an element an id attribute; this value is unique on the page. In JavaScript we select that element with document.getElementById(id).

Example: to select <button id="save">Save</button> we write const saveBtn = document.getElementById("save");.

The argument is a plain string; the # sign is NOT used. This method returns a single element; if it cannot find it, it returns null.

When the element is not found: null

If getElementById cannot find an element with the given id, it returns null. This happens when the page has not loaded yet or the id is misspelled.

Accessing properties on a null value throws a TypeError. So it is safer to check the element first:

const btn = document.getElementById("save");
if (btn) { btn.textContent = "Save"; }

Exercise Select the element and update it safely

Select the element with id "message" using getElementById and assign it to msg. Then check with if (msg); inside it, set msg.textContent to "Hello".

Show example solution
First select with getElementById, then check with if (msg), inside set textContent.
Example solution:
const msg = document.getElementById("message");
if (msg) {
  msg.textContent = "Hello";
}

Test yourself

  1. Select the element with id "page-header"

    const header = document.____("page-header");
    • querySelectorById
    • getElementById
    • findById
    • getId
    Show answer

    getElementById — Correct! getElementById selects a single element by id.

  2. Select an element by id

    // Select the button with id "save"
    const saveBtn = document.____);
    Show answer
    // Select the button with id "save"
    const saveBtn = document.getElementById('save'));
  3. Why use an if (btn) check?

    • Without if the code does not compile
    • if finds the element automatically
    • Accessing a property on null throws a TypeError
    • if runs faster
    Show answer

    Accessing a property on null throws a TypeError — Correct! Accessing a property on a null value throws a TypeError.

All lessons in Intermediate