Find a Document Element
Find a Document Element
querySelector finds the first matching element and returns null when no element matches. Use an ID for a specific school report and check the result before reading its content.
Before this topic, review Understand the DOM Tree if its terms are unfamiliar.
What you’ll learn
- Explain find a document element through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The selector still finds the same element and reads its edited text.
Work through the school example
This is JavaScript in a browser. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
Create this markup in a separate index.html, then place the JavaScript in a script after these elements. Use this isolated practice page so the selectors refer to its markup.
<p id="marks">72</p>JavaScript · browser · complete script for the supplied markup
const report = document.querySelector("#marks");
console.log(report ? report.textContent : "Missing report");
Expected output
72DOM Element Selection in JavaScript
Manipulating web pages dynamically requires us to reach into the DOM (Document Object Model) and grab the elements we want to work with. JavaScript gives us a rich toolbox for doing exactly that. Whether you're adding interactivity, updating content, or styling elements, it all begins with selecting the right elements.
Why Selecting Elements Matters
Before any styling, animation, or dynamic interaction can occur, you must first access the element. Think of it as finding the right wire in a control panel before flipping the switch. This tutorial will teach you how to find that wire confidently and efficiently using JavaScript.
1. document.getElementById()
This method is used to select a single element by its unique id.
const heading = document.getElementById("main-title");
console.log(heading.textContent);
Welcome to My Website
Explanation
If your HTML has <h1 id="main-title">Welcome to My Website</h1>, this method selects that specific element. Fast and efficient when you know the exact ID.
2. document.getElementsByClassName()
Use this to select all elements sharing the same class. It returns an HTMLCollection (like an array but not quite).
const items = document.getElementsByClassName("list-item");
console.log(items[0].textContent);
Item 1
Explanation
Given multiple <li class="list-item"> elements, this lets you loop or access specific ones using index notation. It’s perfect for batch updates.
3. document.getElementsByTagName()
Targets elements based on their tag name like div, p, or ul.
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length);
3
Explanation
Returns all <p> tags on the page. You can use this when you're targeting all elements of a certain type, like for text formatting or layout logic.
4. document.querySelector()
This method uses CSS-style selectors and returns the first matching element.
const firstButton = document.querySelector(".btn-primary");
console.log(firstButton.textContent);
Submit
Explanation
Perfect for precise targeting using class, ID, or nested selectors like div.container h2. Clean, modern, and very readable.
5. document.querySelectorAll()
This returns a static NodeList of all matching elements.
const links = document.querySelectorAll("nav a");
links.forEach(link => console.log(link.href));
https://example.com/home
https://example.com/about
https://example.com/contact
Explanation
Use this when you want to loop over a group of elements that match a specific CSS pattern. It gives you more flexibility than getElementsBy*.
6. Difference Between HTMLCollection and NodeList
Let’s break down the key differences between what these two return types offer:
- HTMLCollection – Live, updates with DOM changes, returned by
getElementsBy*. - NodeList – Static, doesn't update after DOM changes, returned by
querySelectorAll.
7. Looping Through Selected Elements
If you're using getElementsByClassName or getElementsByTagName, convert the result to an array to use forEach.
const items = Array.from(document.getElementsByClassName("menu-item"));
items.forEach(item => item.style.color = "blue");
8. Selecting Nested Elements
Combine methods to get specific nested elements:
const card = document.querySelector(".card");
const cardTitle = card.querySelector("h3");
console.log(cardTitle.textContent);
Product Title
Recognize the important boundary
querySelectorAll returns a static collection; some getElementsBy methods return live collections. Select after the relevant markup exists.
Try a small variation
JavaScript · original source for practice
const report = document.querySelector("#marks");
console.log(report ? report.textContent : "Missing report");
Your task: Replace >72< with >80<. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Markup used by this section:
<p id="marks">72</p>Worked answer and reasoning
The selector still finds the same element and reads its edited text.
Markup for this edited program:
<p id="marks">80</p>JavaScript · complete worked variation
const report = document.querySelector("#marks");
console.log(report ? report.textContent : "Missing report");
Expected output
80Predict the original program
JavaScript · original program for this question
const report = document.querySelector("#marks");
console.log(report ? report.textContent : "Missing report");
Markup used by this section:
<p id="marks">72</p>Keep the useful idea
querySelector finds the first matching element and returns null when no element matches. Use an ID for a specific school report and check the result before reading its content.
Check your variation against this explanation: The selector still finds the same element and reads its edited text.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.