DOM Selectors: getElementById, querySelector, and More
To effectively manipulate the Document Object Model (DOM) with JavaScript, your first step is always to select the HTML elements you want to interact with. JavaScript provides several methods to query the DOM and retrieve references to one or more elements based on their ID, class, tag name, or more complex CSS selectors.
Understanding these selection methods is fundamental to making your web pages interactive.
1. Traditional DOM Selection Methods
These methods have been around for a long time and are still perfectly valid, especially when you need to select elements by a very specific attribute like id. They generally return live HTMLCollections.
a) document.getElementById()
- Purpose: Selects a single element by its unique
idattribute. - Returns: The
Elementobject if found, ornullif no element with thatidexists. - Key Point: IDs must be unique within an HTML document. If multiple elements have the same ID (which is invalid HTML), this method will return only the first one it encounters.
b) document.getElementsByClassName()
- Purpose: Selects all elements that have a specific class name.
- Returns: A live
HTMLCollectionof elements. AnHTMLCollectionis an array-like object (you can iterate over it withfor...ofor convert it to an array, but notforEachdirectly unless converted) that updates automatically if the DOM changes.
c) document.getElementsByTagName()
- Purpose: Selects all elements with a given tag name (e.g.,
<div>,<p>,<a>). - Returns: A live
HTMLCollectionof elements.
2. Modern DOM Selection Methods (CSS Selectors)
Introduced with the Selectors API, these methods are more powerful and flexible because they allow you to use standard CSS selectors to find elements.
a) document.querySelector()
- Purpose: Selects the first element that matches a specified CSS selector (or a group of selectors).
- Returns: The
Elementobject if a match is found, ornullif no match. - Flexibility: You can use any valid CSS selector string: IDs (
#myId), classes (.myClass), tag names (div), attribute selectors ([data-value="123"]), pseudo-classes (:hover), descendant selectors (.container p), etc.
b) document.querySelectorAll()
- Purpose: Selects all elements that match a specified CSS selector (or a group of selectors).
- Returns: A static
NodeListof elements. ANodeListis also an array-like object, but unlikeHTMLCollection, it is a “snapshot” of the DOM at the time of the query and does not automatically update if elements are added or removed from the DOM later.
3. HTMLCollection vs. NodeList (Live vs. Static)
This is an important distinction when dealing with collections of elements:
HTMLCollection(Live): Returned bygetElementsByClassNameandgetElementsByTagName. If you add or remove elements that match the criteria after you’ve queried them, theHTMLCollectionwill automatically reflect those changes.NodeList(Static): Returned byquerySelectorAll. It is a snapshot. If elements matching the selector are added or removed after the query, theNodeListwill not update.
Most modern development favors querySelector and querySelectorAll due to their flexibility with CSS selectors, but it’s crucial to remember that querySelectorAll gives you a static list. If you need a live list, or maximum performance for ID lookups, the traditional methods still have their place.
Exercise: Select and Log!
Instructions:
Given the following (simulated) HTML structure, use different DOM selection methods to retrieve the specified elements and log their textContent.
<div id="main-content">
<h2 class="section-title">Welcome to our site!</h2>
<div class="card product-card">
<p>Product A description.</p>
<button class="add-to-cart" data-id="123">Add to Cart</button>
</div>
<div class="card promo-card">
<p>Special offer!</p>
<a href="#" class="btn view-details">View Details</a>
</div>
<ul id="navigation">
<li>Home</li>
<li class="active">About</li>
<li>Contact</li>
</ul>
</div>
<span class="copyright">© 2025 MyCompany</span>
Your Task:
- Select the
<h2>element using its class and log its text. - Select the button with
data-id="123"using a CSS attribute selector and log its text. - Select all
<div>elements with the classcardand log the text content of each. - Select the list item (
<li>) with the classactiveand log its text.

