Course contentsShow
← Web Development
Lesson 675 of 2,98212. The Document Object ModelFree lesson

document.getElementById()

Select a single element by its unique ID attribute, the most specific selection method.

What You'll Learn

You'll learn how to select a single element from the DOM by its unique id attribute — the most direct and efficient way to grab one specific element on the page.

The Most Specific Selector

Think of the DOM as a phone book, and every element's id is like a unique phone number. When you need to reach exactly one person, you don't flip through pages—you dial their number directly. That's what document.getElementById() does: it finds the one element with that exact id and hands it to you.

This method takes a single string argument—the id value (without the # symbol)—and returns the matching element or null if nothing matches.

How It Works

// HTML: <div id="header">Welcome</div>

const headerElement = document.getElementById('header');
console.log(headerElement); // <div id="header">Welcome</div>

Notice:

  • The id value must be unique in your HTML document
  • You pass the id as a plain string, not "#header"
  • You get back one element or null (never a collection)

Why Use IDs for Selection?

Because id attributes must be unique, this method is:

  • Fast: The browser can locate the element instantly
  • Specific: You get exactly what you expect
  • Simple: Perfect for landmark elements like headers, main content areas, or forms
const mainContent = document.getElementById('main-content');
const loginForm = document.getElementById('login-form');
const errorMessage = document.getElementById('error-display');

Key Takeaway: document.getElementById() is your go-to method for selecting a single, uniquely-identified element by its id attribute—fast, direct, and unambiguous.