🔍 DOM Selectors
Last Updated: 26th October 2025
- DOM selectors are methods that allow you to access HTML elements so you can manipulate them with JavaScript.
- Think of them as ways to “point” to specific elements in the DOM tree.
Hinglish Tip 🗣: Agar DOM ek tree hai, toh selectors wo tools hain jo batate hain “main kaunse leaf ya branch ko touch karna chahta hoon.”
🧩 Common DOM Selection Methods
document.getElementById()
- Select one element by its ID.
- Returns a single element (or
nullif not found).
<h1 id="title">Hello World</h1>
<script>
const heading = document.getElementById("title");
console.log(heading.textContent); // Output: Hello World
</script>
document.getElementsByClassName()
- Select all elements with a specific class.
- Returns an HTMLCollection (array-like).
<p class="para">Paragraph 1</p>
<p class="para">Paragraph 2</p>
<script>
const paras = document.getElementsByClassName("para");
console.log(paras.length); // 2
console.log(paras[0].textContent); // Paragraph 1
</script>
document.getElementsByTagName()
- Select all elements with a specific tag name.
- Returns an HTMLCollection.
<p>One</p>
<p>Two</p>
<script>
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // 2
console.log(paragraphs[1].textContent); // Two
</script>
document.querySelector()
- Selects first element that matches a CSS selector.
- Returns a single element.
<p class="para">Hello</p>
<script>
const firstPara = document.querySelector(".para");
console.log(firstPara.textContent); // Hello
</script>
document.querySelectorAll()
- Selects all elements that match a CSS selector.
- Returns a NodeList (collection of elements),you can use forEach loop .
<p class="para">Para 1</p>
<p class="para">Para 2</p>
<script>
const allParas = document.querySelectorAll(".para");
allParas.forEach((p) => console.log(p.textContent));
// Output:
// Para 1
// Para 2
</script>
Hinglish Tip 🗣: querySelector aur querySelectorAll sabse flexible hai kyunki CSS selector style use karte hain.
💡 Quick Practice
- Get element with ID title and change its text.
- Select all elements with class para and make their text uppercase.
- Try selecting the first <p> inside a <div> using querySelector.