When working with JavaScript DOM manipulation, selecting elements correctly is very important. Two commonly used methods are getElementsByClassName and querySelector. Although both are used to select elements from the DOM, they behave differently.
Let’s understand them with simple examples.
🔹 getElementsByClassName
✅ What it does
Selects all elements with a given class name
Returns an HTMLCollection (array-like object)
Example
<h1 class="title">Hello</h1>
<h1 class="title">Welcome</h1>
let elements = document.getElementsByClassName("title");
console.log(elements);
🔍 Important points
You must access elements using index
`elements[0].innerText = "Changed";
To update all elements, you need a loop
for (let i = 0; i < elements.length; i++) {
elements[i].innerText = "Updated";
}`
🔹 querySelector
✅ What it does
- Selects the first matching element
- Uses CSS selector syntax
- Returns a single element
Example
let element = document.querySelector(".title");
element.innerText = "Changed";
✔ No loop needed
✔ Cleaner and simpler
🔹 querySelectorAll
If you want all matching elements, use:
let elements = document.querySelectorAll(".title");
elements.forEach(el => el.innerText = "Updated");
Returns a NodeList
Top comments (0)