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 IDdocument.getElementsByClassName("class")
β Returns a live HTMLCollectiondocument.getElementsByTagName("tag")
β Returns elements by tag namedocument.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.