Selecting Elements: getElementById, querySelector0%
Selecting Elements: getElementById, querySelector
Beginner12 min read•Updated: Jul 11, 2026
Selecting Elements: getElementById and querySelector
The DOM (Document Object Model) is a tree-like representation of an HTML document created by the browser. To make web pages interactive with JavaScript, the very first step is selecting the HTML elements you want to inspect, manipulate, or listen to.
1. The DOM Tree Mental Model
Output
document (Root)
└── <html>
├── <head>
│ └── <title>
└── <body>
├── <header>
│ └── <h1 id="main-title">
└── <main>
├── <button class="btn btn-primary">
└── <p class="description">
2. Classic Selection Methods
A. document.getElementById('id')
Selects a single unique element by its id attribute. Returns the element or null:
JavaScript
// HTML: <h1 id="main-title">Welcome</h1>
const heading = document.getElementById("main-title");
console.log(heading); // <h1>Welcome</h1>
Note
[!NOTE]
Do not include
# when using getElementById()! Just pass the plain ID string: "main-title".B. document.getElementsByClassName('class')
Returns an HTMLCollection (array-like, live list) of all matching elements:
JavaScript
// HTML: <p class="text">One</p> <p class="text">Two</p>
const paragraphs = document.getElementsByClassName("text");
3. Modern Selection Methods: querySelector & querySelectorAll
Modern web development uses CSS selectors with two standardized methods:
Visual Architecture Blueprint
+-----------------------------------------------------------------------------+
| MODERN DOM SELECTOR METHODS |
+-----------------------------------------------------------------------------+
| document.querySelector("selector") |
| -> Returns the FIRST matching element found in document (or null) |
| |
| document.querySelectorAll("selector") |
| -> Returns a static NodeList of ALL matching elements |
+-----------------------------------------------------------------------------+Supported CSS Selectors:
- By Tag Name:
document.querySelector("h1") - By ID (
#):document.querySelector("#main-title") - By Class (
.):document.querySelector(".btn-primary") - By Attribute (
[...]):document.querySelector("input[type='email']") - Complex Hierarchical:
document.querySelector("nav ul > li.active a")
Example: Selecting Multiple Elements with querySelectorAll:
querySelectorAll returns a NodeList which supports modern array methods like .forEach():
JavaScript
const cards = document.querySelectorAll(".course-card");
cards.forEach((card, index) => {
console.log(`Card ${index}:`, card);
});
4. Selection Best Practices Comparison
| Method | Syntax | Return Type | Supports Complex Selectors? |
|---|---|---|---|
getElementById | getElementById('nav') | Single Element | No (ID only, fastest) |
querySelector | querySelector('#nav') | Single Element (First) | Yes (Any CSS selector) |
querySelectorAll | querySelectorAll('.card') | Static NodeList | Yes (Any CSS selector) |
Interactive Quiz
Practice Quiz
Question 1
What does
document.getElementById("submit-btn") return if no element has that ID?Question 2
How does
document.querySelector(".active") differ from document.querySelectorAll(".active")?Question 3
Which symbol must prefix a class name when selecting with
document.querySelector?Question 4
Which symbol prefixes an ID selector in
document.querySelector?Question 5
Can you directly call
.forEach() on the result of document.querySelectorAll()?Next Lesson
Changing Content and Style
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Random Numbers Example | Changing Content and Style |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.