- Selecting elements by ID
- Selecting elements by class name
- Selecting elements by tag name
- Selecting elements using CSS selectors
Selecting Elements by ID
const element = document.getElementById("myElementId");
This method will return the first element with the given ID, or null if no such element is found.
Selecting Elements by Class Name
To select elements based on their class name, we can use the getElementsByClassName() method. This will return an HTMLCollection of elements with the matching class name.
const elements = document.getElementsByClassName("myClassName");
Since this method returns an HTMLCollection, you can access individual elements by their index or loop through the collection using a for loop.
Selecting Elements by Tag Name
Similar to selecting elements by class name, you can also select elements based on their tag name. This is done using the getElementsByTagName() method.
const elements = document.getElementsByTagName("p");
Like the getElementsByClassName() method, this method also returns an HTMLCollection of elements with the matching tag name.
Selecting Elements Using CSS Selectors
The querySelector() method returns the first element that matches the specified CSS selector, while the querySelectorAll() method returns a NodeList of all matching elements.
const firstElement = document.querySelector(".myClassName"); const allElements = document.querySelectorAll(".myClassName");
These methods allow you to query elements with a high level of specificity, using any valid CSS selector.