JavaScript Document getElementById() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.getElementById() is an instance method that returns the Element whose id matches a string (see MDN Document: getElementById()). Learn the id parameter, null when missing, case sensitivity, why spelling is Id (not ID), how it compares to querySelector, and five try-it labs.

01

Kind

Instance method

02

Arg

id (string)

03

Returns

Element | null

04

IDs

must be unique

05

Case

sensitive

06

Status

Baseline

Introduction

Almost every beginner DOM demo starts here: give an element an id, then grab it with document.getElementById("..."). Because IDs should be unique in a document, this is a fast, clear way to reach one specific node.

MDN: the method returns an Element whose id property matches the specified string. If you need an element without an ID, use querySelector() with any CSS selector instead.

💡
Think: look up by name badge

1) Put id="para" on an element in HTML
2) Call document.getElementById("para")
3) Get the element — or null if missing
4) Update text, style, or listeners

Related tutorials: createElement(), getAnimations(), getElementsByClassName().

Understanding document.getElementById()

An instance method on the global document object (MDN Document interface).

  • id — case-sensitive string unique within the document (MDN).
  • Return value — matching Element, or null if not found (MDN).
  • Uniqueness — IDs should be unique; if duplicates exist, the first match is returned (MDN).
  • Spelling — must be getElementById; getElementByID is invalid (MDN).
  • Document only — not available on arbitrary element objects (MDN usage notes).
  • In-tree only — elements not yet inserted into the document are not found (MDN).

📝 Syntax

General form of Document.getElementById (MDN):

JavaScript
getElementById(id)

Parameters

  • id — the ID of the element to locate. Case-sensitive string; only one element should have any given ID (MDN).

Return value

An Element matching the specified ID, or null if no matching element was found (MDN).

Capitalization note (MDN)

The letters Id must be spelled exactly that way. getElementByID() will not work, even though it looks natural.

MDN color-change example

JavaScript
function changeColor(newColor) {
  const elem = document.getElementById("para");
  elem.style.color = newColor;
}

document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    changeColor(event.target.textContent.toLowerCase());
  });
});

⚡ Quick Reference

GoalCode
Find by iddocument.getElementById("para")
Null-safeconst el = document.getElementById("x"); if (el) { ... }
Change textdocument.getElementById("msg").textContent = "Hi"
Wrong spellinggetElementByID — does not work (MDN)
No id?document.querySelector(".card") (MDN)
MDN statusBaseline Widely available (since Jul 2015)

🔍 At a Glance

Four facts about document.getElementById().

Returns
Element | null

MDN

Arg
id

string

Case
sensitive

Main ≠ main

Status
Baseline

since 2015

📋 Common pitfalls

SituationResultFix
Wrong capitalization getElementByIDMethod missing / error (MDN)Use getElementById
Case mismatch "Main" vs id="main"null (MDN)Match exact spelling
Element created but not insertednull (MDN)Append to the document first
Duplicate ids in the pageFirst match only (MDN)Keep ids unique
Call on a parent elementNot available (MDN)Always use document.getElementById

Examples Gallery

Examples follow MDN Document: getElementById() and practical beginner patterns.

📚 Getting Started

Find an element by id and update it.

Example 1 — MDN: change paragraph color

Look up #para and set style.color from button labels.

JavaScript
function changeColor(newColor) {
  const elem = document.getElementById("para");
  elem.style.color = newColor;
}

document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    changeColor(event.target.textContent.toLowerCase());
  });
});
Try It Yourself

How It Works

MDN’s sample stores the looked-up element in elem, then updates CSS through the DOM style object.

Example 2 — Always check for null

Missing ids return null — guard before using the element.

JavaScript
const el = document.getElementById("missing");
if (el) {
  console.log(el.textContent);
} else {
  console.log("no element with that id");
}
Try It Yourself

How It Works

Reading .textContent on null throws. MDN’s return value is explicitly Element or null.

📈 Practical Patterns

Case rules, detached nodes, and selector alternatives.

Example 3 — Case-sensitive ids

MDN: "Main" does not match id="main".

JavaScript
// HTML: 
Hello
console.log(document.getElementById("main") !== null); // true console.log(document.getElementById("Main") !== null); // false
Try It Yourself

How It Works

Treat the id string as an exact match. Prefer consistent lowercase ids in HTML and JavaScript to avoid this class of bugs.

Example 4 — Element not yet in the document

MDN: create + assign id is not enough until you insert the node.

JavaScript
const element = document.createElement("div");
element.id = "test";
console.log(document.getElementById("test")); // null

document.body.appendChild(element);
console.log(document.getElementById("test") !== null); // true
Try It Yourself

How It Works

getElementById searches the document tree. Keep a local variable reference after createElement, or append before looking up by id.

Example 5 — Same node via querySelector("#id")

Both can find an id; getElementById stays the classic path.

JavaScript
const byId = document.getElementById("hero");
const bySel = document.querySelector("#hero");
console.log(byId === bySel); // true when both find the same node
Try It Yourself

How It Works

MDN recommends querySelector when you do not have an id. For a known unique id, getElementById is clear and widely used.

🚀 Common Use Cases

  • Form fields — read value from #email / #password.
  • UI updates — change text or class on a status banner.
  • Event wiring — attach listeners to a known button id.
  • Tutorial demos — the simplest way to connect HTML and JavaScript.
  • Not class lookups — use querySelector / getElementsByClassName.
  • Not local searches — MDN: no element-level getElementById.

🧠 How getElementById() Works

1

Pass an id string

Exact, case-sensitive match for the element’s id attribute (MDN).

Input
2

Search the document

Only nodes in the document tree are considered (MDN).

Lookup
3

First unique match

IDs should be unique; duplicates yield the first found element (MDN).

Match
4

Element or null

Use the node safely after a null check.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • MDN: spelling is getElementById — not getElementByID.
  • MDN: id matching is case-sensitive.
  • MDN: available on document, not on every element.
  • MDN: detached nodes (created but not inserted) are not found.
  • Related: createElement(), getAnimations(), getElementsByClassName().

Browser Support

Document.getElementById() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.getElementById()

The classic DOM lookup by unique id — Element or null across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
getElementById() Wide

Bottom line: Use getElementById for unique ids. Prefer querySelector when you need classes, attributes, or complex selectors.

Conclusion

document.getElementById(id) is the fastest mental model for grabbing one unique node: pass the id, get an Element or null. Keep ids unique, match case exactly, spell the method Id, and fall back to querySelector when you do not have an id.

Continue with createElement(), getElementsByClassName(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Keep every id unique in the document (MDN)
  • Null-check before reading properties
  • Match id casing exactly in HTML and JavaScript
  • Use meaningful ids (signup-form, not div1)
  • Prefer querySelector when selecting by class or structure (MDN)

❌ Don’t

  • Write getElementByID (capital D) — it will not work (MDN)
  • Assume a fresh createElement is findable before insert (MDN)
  • Call getElementById on a parent element (not available) (MDN)
  • Reuse the same id on multiple nodes
  • Skip null checks in production UI code

Key Takeaways

Knowledge Unlocked

Five things to remember about getElementById()

Find one unique element by id — or get null.

5
Core concepts
🔄02

Case

sensitive

exact
✍️03

Spelling

Id not ID

MDN
04

Alt

querySelector

no id
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.getElementById() returns an Element whose id property matches the specified string, or null if no matching element is found. IDs should be unique in a document.
No. MDN marks Document.getElementById() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
The method returns null (MDN). Always check for null before reading properties like textContent or style.
Yes. MDN: the id string is case-sensitive. document.getElementById("Main") will not find an element with id="main".
MDN: capitalization of "Id" must be correct. getElementByID() is not valid and will not work.
MDN: if the element has no id, use querySelector() with any CSS selector. getElementById() is still the classic, fast path when you have a unique id.
Did you know?

MDN’s usage notes show why there is no parent.getElementById(): ids must be unique in the whole document, so a “local” search would not make sense the way class or tag lookups do.

Next: getElementsByClassName()

Learn how to collect every element that shares one or more class names into a live HTMLCollection.

getElementsByClassName() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful