HomeJAVASCRIPTHow do you select elements in DOM?

How do you select elements in DOM?

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 name attribute (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

MethodReturnsLive/Static
getElementById()Element (single)
getElementsByClassName()HTMLCollectionLive
getElementsByTagName()HTMLCollectionLive
getElementsByName()NodeListLive
querySelector()First matching elementStatic
querySelectorAll()NodeList (all)Static

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *