Phase 10 — DOM (Very Important)
Module 31 — Selecting DOM Elements
Selecting elements is one of the most important skills in JavaScript. Before you can modify content, change styles, handle events, or create animations, you must first select the required HTML elements.
JavaScript provides several methods to find elements in the DOM.
Overview
| Method | Returns | Best Use |
|---|---|---|
getElementById() | Single Element | Select by unique ID |
getElementsByClassName() | HTMLCollection | Select elements with same class |
getElementsByTagName() | HTMLCollection | Select by HTML tag |
querySelector() | First Matching Element | CSS selectors |
querySelectorAll() | NodeList | Multiple CSS selector matches |
closest() | Closest Ancestor | Event delegation |
matches() | Boolean | Check if element matches selector |
document.getElementById()
Returns the element with the specified id.
HTML
1<h1 id="title">JavaScript DOM</h1>
JavaScript
1const heading = document.getElementById("title"); 2 3console.log(heading);
Change Content
1heading.textContent = "DOM Tutorial";
Best Use
- Navigation
- Forms
- Single unique elements
document.getElementsByClassName()
Returns a live HTMLCollection.
HTML
1<p class="item">Apple</p> 2 3<p class="item">Banana</p> 4 5<p class="item">Orange</p>
JavaScript
1const items = document.getElementsByClassName("item"); 2 3console.log(items);
Access elements
1console.log(items[0]);
Loop through
1for (let item of items) { 2 3 console.log(item.textContent); 4 5}
document.getElementsByTagName()
Selects all elements having the specified HTML tag.
1<h2>One</h2> 2 3<h2>Two</h2> 4 5<h2>Three</h2>
1const headings = document.getElementsByTagName("h2"); 2 3console.log(headings);
document.querySelector()
Returns the first matching element.
1<div class="card"> 2 3 <h2>JavaScript</h2> 4 5</div>
1const card = document.querySelector(".card"); 2 3console.log(card);
Using ID
1document.querySelector("#title");
Using Tag
1document.querySelector("h2");
Using Attribute
1document.querySelector("[type='text']");
document.querySelectorAll()
Returns all matching elements as a NodeList.
1const paragraphs = document.querySelectorAll("p");
Loop
1paragraphs.forEach(paragraph => { 2 3 console.log(paragraph.textContent); 4 5});
querySelector() vs querySelectorAll()
| Method | Returns |
|---|---|
querySelector() | First Match |
querySelectorAll() | All Matches |
Example
1document.querySelector(".item"); 2 3document.querySelectorAll(".item");
closest()
Returns the nearest ancestor that matches the selector.
HTML
1<div class="card"> 2 3 <button class="btn"> 4 5 Click 6 7 </button> 8 9</div>
JavaScript
1const button = document.querySelector(".btn"); 2 3const card = button.closest(".card"); 4 5console.log(card);
Used extensively in:
- Event Delegation
- Modals
- Tables
- Menus
matches()
Checks whether an element matches a CSS selector.
1const button = document.querySelector(".btn"); 2 3console.log( 4 5button.matches(".btn") 6 7);
Output
1true
Another Example
1console.log( 2 3button.matches("h1") 4 5);
Output
1false
Practical Example
HTML
1<div class="container"> 2 3 <h1 id="title"> 4 5 JavaScript 6 7 </h1> 8 9 <p class="text"> 10 11 Learn DOM 12 13 </p> 14 15 <p class="text"> 16 17 Practice Daily 18 19 </p> 20 21</div>
JavaScript
1const title = document.getElementById("title"); 2 3const texts = document.querySelectorAll(".text"); 4 5title.style.color = "blue"; 6 7texts.forEach(text => { 8 9 console.log(text.textContent); 10 11});
Real-World Example — Navigation Menu
1<nav> 2 3 <a class="link">Home</a> 4 5 <a class="link">About</a> 6 7 <a class="link">Contact</a> 8 9</nav>
1const links = document.querySelectorAll(".link"); 2 3links.forEach(link => { 4 5 link.style.fontWeight = "bold"; 6 7});
Mini Project — Highlight Selected Elements
index.html
1<!DOCTYPE html> 2<html> 3 4<head> 5 6<title>DOM Selection</title> 7 8</head> 9 10<body> 11 12<h2 id="heading"> 13 14JavaScript 15 16</h2> 17 18<p class="item">HTML</p> 19 20<p class="item">CSS</p> 21 22<p class="item">JavaScript</p> 23 24<button id="btn"> 25 26Highlight 27 28</button> 29 30<script src="script.js"></script> 31 32</body> 33 34</html>
script.js
1const button = document.getElementById("btn"); 2 3const items = document.querySelectorAll(".item"); 4 5button.addEventListener("click", () => { 6 7 items.forEach(item => { 8 9 item.style.background = "yellow"; 10 11 }); 12 13});
Common Mistakes
Forgetting # in querySelector()
❌ Wrong
1document.querySelector("title");
✅ Correct
1document.querySelector("#title");
Treating HTMLCollection Like an Array
❌ Wrong
1const items = document.getElementsByClassName("item"); 2 3items.forEach(...);
Use
1Array.from(items).forEach(item => { 2 3 console.log(item); 4 5});
or use querySelectorAll().
Using Duplicate IDs
Each id should be unique.
❌ Wrong
1<h1 id="title"></h1> 2 3<h2 id="title"></h2>
Best Practices
- Use
getElementById()when selecting a single unique element. - Prefer
querySelector()andquerySelectorAll()because they support CSS selectors. - Use
querySelectorAll()when working with multiple elements andforEach(). - Use
closest()for event delegation and finding parent containers. - Use
matches()to check whether an element satisfies a selector before performing operations. - Avoid duplicate
idvalues in HTML. - Cache frequently used DOM elements instead of selecting them repeatedly.
Interview Questions
Q1. What is the difference between getElementById() and querySelector()?
getElementById()selects an element by its unique ID.querySelector()accepts any valid CSS selector and returns the first matching element.
Q2. What is the difference between HTMLCollection and NodeList?
HTMLCollectionis a live collection of elements.NodeListreturned byquerySelectorAll()is usually static and supportsforEach().
Q3. What does closest() do?
It searches upward from the current element and returns the nearest ancestor that matches the specified CSS selector.
Q4. What is matches() used for?
It returns true if the element matches the given CSS selector; otherwise, it returns false.
Summary
In this module, you learned:
- How to select elements using
getElementById(),getElementsByClassName(), andgetElementsByTagName(). - How to use
querySelector()andquerySelectorAll()with CSS selectors. - The difference between
HTMLCollectionandNodeList. - How
closest()finds matching ancestor elements. - How
matches()checks whether an element satisfies a CSS selector. - Best practices for efficient and maintainable DOM element selection.
Next Module: Module 32 — DOM Manipulation, where you'll learn
textContent,innerHTML,innerText,setAttribute(),classList,style,createElement(),append(),prepend(),remove(), and other essential DOM manipulation techniques used in professional web development.