SmartCodingTips

DOM Selectors in JavaScript

DOM selectors are methods used to access elements in the HTML document. These allow JavaScript to read and manipulate the content, structure, and style of elements.

πŸ” Common DOM Selection Methods

  • document.getElementById("id") – Selects a single element by its ID
  • document.getElementsByClassName("class") – Returns a live HTMLCollection
  • document.getElementsByTagName("tag") – Returns elements by tag name
  • document.querySelector("selector") – Selects the first match (CSS-style)
  • document.querySelectorAll("selector") – Selects all matches (NodeList)

πŸ“˜ Examples

<div id="main" class="box">Hello</div>
<p class="text">Paragraph</p>
<p class="text">Another</p>

const el1 = document.getElementById("main");
const el2 = document.getElementsByClassName("text"); // HTMLCollection
const el3 = document.querySelector(".text"); // First <p>
const el4 = document.querySelectorAll(".text"); // NodeList of both <p>

🧠 NodeList vs HTMLCollection

HTMLCollection is live β€” it updates automatically when the DOM changes. NodeList from querySelectorAll is static β€” it doesn’t auto-update.

πŸ” Looping Through NodeLists

document.querySelectorAll(".text").forEach(p => {
    console.log(p.textContent);
});
πŸ’‘ Tip: Prefer querySelector and querySelectorAll for flexibility using CSS selectors.