Selecting Elements
Once you understand the DOM, the next step is finding elements inside the page so JavaScript can work with them.
Selecting elements allows JavaScript to read, update, and interact with specific parts of a web page.
Why Selecting Elements Matters
Before changing text, responding to clicks, or validating forms, JavaScript must first select the correct element.
If the element is not selected properly, JavaScript cannot interact with it.
Selecting by ID
The most common and fastest way to select an element
is by using its unique id.
let title = document.getElementById("mainTitle");
IDs must be unique on a page, which makes this method reliable.
Selecting by Class Name
When multiple elements share the same class,
you can select them using getElementsByClassName().
let buttons = document.getElementsByClassName("btn");
This returns a collection of elements, not just one.
Selecting by Tag Name
You can also select elements by their HTML tag name.
let paragraphs = document.getElementsByTagName("p");
This is useful when working with groups of similar elements.
Using querySelector()
querySelector() selects the first element
that matches a CSS selector.
let header = document.querySelector(".header");
It provides more flexibility and works like CSS.
Using querySelectorAll()
querySelectorAll() selects all elements
that match a CSS selector.
let items = document.querySelectorAll(".menu-item");
This returns a list of matching elements.
Real-World Example
Imagine changing a button text when a page loads:
let button = document.getElementById("submitBtn");
button.innerText = "Send Now";
This simple action improves user experience.
Common Beginner Mistakes
- Using an ID that does not exist
- Forgetting that class selection returns multiple elements
- Trying to modify elements before the page loads
Always ensure the element exists before using it.
Thumb Rules
- Use
getElementById()for unique elements - Use
querySelector()for flexibility - Understand whether you are selecting one or many elements
- Keep selectors simple and readable
What Comes Next?
Now that you know how to select elements, the next step is changing them.
In the next lesson, we will learn how to modify the DOM.