In the DOM (Document Object Model), we can select elements using different methods provided by JavaScript. Here are the most commonly used ones:
1. By ID
document.getElementById("myId");
- Returns a single element with the specified ID.
- IDs must be unique in a document.
2. By Class Name
document.getElementsByClassName("myClass");
- Returns an HTMLCollection (live list) of elements with the given class name.
- Access with index:
document.getElementsByClassName("myClass")[0].
3. By Tag Name
document.getElementsByTagName("div");
- Returns an HTMLCollection of elements with the specified tag.
4. By Name Attribute
document.getElementsByName("username");
- Returns a NodeList of elements with the given
nameattribute (often used in forms).
5. Using Query Selector (CSS selectors)
document.querySelector(".myClass"); // First element with class
document.querySelector("#myId"); // First element with ID
document.querySelector("div > p"); // First <p> inside a <div>
- Returns the first matching element.
6. Using Query Selector All (CSS selectors)
document.querySelectorAll(".myClass");
- Returns a NodeList (static list) of all matching elements.
- Can be looped with
forEach.
✅ Summary Table
| Method | Returns | Live/Static |
|---|---|---|
getElementById() | Element (single) | – |
getElementsByClassName() | HTMLCollection | Live |
getElementsByTagName() | HTMLCollection | Live |
getElementsByName() | NodeList | Live |
querySelector() | First matching element | Static |
querySelectorAll() | NodeList (all) | Static |
