Searching Elements in the DOM – getElement* vs. querySelector* in JavaScript

Searching Elements in the DOM – getElement* vs. querySelector* in JavaScript

Searching Elements in the DOM – getElement* vs. querySelector* in JavaScript

JavaScript provides multiple ways to search and select elements in the Document Object Model (DOM). The two primary methods are:

  1. getElement* methods (older, but optimized for speed)
  2. querySelector* methods (modern and more flexible)

🔹 1. getElementById(id) – Fastest Way to Get a Single Element

  • Selects an element with a specific id.
  • Returns a single element (or null if not found).

Example: Selecting an element by id

let title = document.getElementById("main-title"); console.log(title.innerText); // Logs the text inside the element

Note: IDs must be unique in an HTML document.

🔹 2. getElementsByClassName(className) – Select Multiple Elements

  • Selects all elements with a given class.
  • Returns an HTMLCollection (live list, updates automatically if DOM changes).

Example: Selecting elements by class

let items = document.getElementsByClassName("list-item"); console.log(items.length); // Logs the number of elements found console.log(items[0].innerText); // Access first element

🔹 Convert to an Array for easier manipulation:

Array.from(items).forEach(item => console.log(item.innerText));

🔹 3. getElementsByTagName(tagName) – Select Elements by Tag

  • Selects all elements with a given tag name.
  • Returns an HTMLCollection.

Example: Selecting all <p> elements

let paragraphs = document.getElementsByTagName("p"); console.log(paragraphs.length); // Logs the number of <p> elements

🔹 Convert to an array and loop through elements:

[...paragraphs].forEach(p => console.log(p.innerText));

🔹 4. querySelector(selector) – Select the First Matching Element

  • Uses CSS selectors to find elements.
  • Returns only the first matching element (or null if none found).

Example: Selecting the first <div> with my-class

let element = document.querySelector("div.my-class"); console.log(element.innerText);

Example: Selecting the first <input> of type checkbox

let checkbox = document.querySelector("input[type='checkbox']"); console.log(checkbox.checked);

🔹 5. querySelectorAll(selector) – Select All Matching Elements

  • Uses CSS selectors to find elements.
  • Returns a NodeList (static, doesn’t update automatically).
  • Can use .forEach() to loop through items.

Example: Selecting all elements with my-class

let elements = document.querySelectorAll(".my-class"); elements.forEach(el => console.log(el.innerText));

Example: Selecting all <input> elements inside a form

let inputs = document.querySelectorAll("form input"); console.log(inputs.length);

🔹 Differences Between getElement* and querySelector*

MethodReturnsLive UpdateSupports CSS SelectorsBest Use Case
getElementById(id)Single Element (null if not found)❌ No❌ NoFastest way to get an element by id
getElementsByClassName(class)HTMLCollection (multiple elements)✅ Yes❌ NoFast when selecting by class
getElementsByTagName(tag)HTMLCollection (multiple elements)✅ Yes❌ NoBest for selecting by tag name
querySelector(selector)First matching element❌ No✅ YesMore flexible, supports complex selectors
querySelectorAll(selector)NodeList (multiple elements)❌ No✅ YesBest for selecting multiple elements

🔹 When to Use What?

Use getElementById when selecting by id (fastest method).
Use querySelector/querySelectorAll for flexible CSS-based selection.
Use getElementsByClassName or getElementsByTagName when performance matters and you need a live list.

🚀 Best practice: Prefer querySelector/querySelectorAll unless performance is a concern.

🔹 Example: Selecting Elements in Different Ways

HTML

<h1 id="title">Hello, World!</h1> <p class="description">This is a paragraph.</p> <p class="description">This is another paragraph.</p> <ul> <li class="list-item">Item 1</li> <li class="list-item">Item 2</li> </ul>

JavaScript

// Using getElementById let title = document.getElementById("title"); console.log(title.innerText); // Using querySelector let firstParagraph = document.querySelector(".description"); console.log(firstParagraph.innerText); // Using querySelectorAll let paragraphs = document.querySelectorAll(".description"); paragraphs.forEach(p => console.log(p.innerText)); // Using getElementsByClassName let items = document.getElementsByClassName("list-item"); Array.from(items).forEach(item => console.log(item.innerText));

🔹 Summary

For Single ElementsgetElementById or querySelector.
For Multiple ElementsgetElementsByClassName, getElementsByTagName, or querySelectorAll.
For More FlexibilityquerySelector/querySelectorAll (supports full CSS selectors).

🚀 Use the right method depending on your needs for better performance and readability!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close