JavaScript get element & find element: getElementById, querySelector, collections

js get element, javascript find element: getElementById, querySelector, querySelectorAll, getElementsByClassName, getElementsByTagName. Snippets use `{run=false}`—run with happy-dom/jsdom and the sample HTML in the article.

Published

Updated

Read time 3 min read

Reviewed byDeepak Prasad

JavaScript get element & find element: getElementById, querySelector, collections

Selecting DOM nodes is the first step in almost every script: grab a single element by stable id, match the first node that satisfies a CSS selector, or fetch every match as a collection. The APIs sound similar—getElementById, querySelector, querySelectorAll, getElementsByTagName, getElementsByClassName—but they differ in return types, live versus static collections, and whether you pass a raw id string or a full selector.

Modern pages mix document.getElementById for stable IDs, document.querySelector / querySelectorAll for CSS selectors, and the classic collection helpers getElementsByTagName and getElementsByClassName. API names are case-sensitive: the middle word is By with a capital B (getElementsByTagName, not getElementsbyTagName). For a side-by-side comparison of these entry points, read JavaScript DOM selectors next.

The runnable snippets below assume a tiny document like the HTML shown here.

html
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>
<p id="alpha">Alpha text</p>
<div id="box"><span>Child</span></div>
<p class="tagged">Tagged</p>
<p>Plain</p>
<input id="inp" value="sample" />
</body>
</html>

Tested on: Node.js v20.18.2 with happy-dom where snippets call document. Fences use {run=false} for the hosted Run control; inject the sample HTML locally.


getElementById for a single ID

When you control a unique id in the markup, getElementById is the narrowest lookup. It returns one element or null if the id is absent.

javascript
console.log(document.getElementById("alpha").innerText);

You should see one line logging Alpha text.

innerHTML returns serialized markup inside the element:

javascript
console.log(document.getElementById("box").innerHTML);

You should see one line logging <span>Child</span>.

For form controls, read the current field value with value, not innerText:

javascript
console.log(document.getElementById("inp").value);

You should see one line logging sample.


querySelector for CSS selectors (find element in JavaScript)

querySelector returns the first element that matches a CSS selector, or null if nothing matches. It covers ids (#alpha), classes (.tagged), tags (p), and combined patterns.

javascript
console.log(document.querySelector("#alpha").innerText);

You should see one line logging Alpha text.

javascript
console.log(document.querySelector(".tagged").innerText);

You should see one line logging Tagged.


querySelectorAll when you need every match (javascript get elements)

querySelectorAll yields a static NodeList of all matching elements—handy when you want every p, every .tagged, or a complex selector.

javascript
console.log(document.querySelectorAll("p").length);

You should see one line logging 3.


getElementsByTagName and getElementsByClassName

Both return an HTMLCollection: an array-like list you can index ([0], [1], …) or loop. The collection for class and tag lookups is live: if the DOM changes, the same collection object reflects the new matches.

javascript
console.log(document.getElementsByTagName("p").length);

You should see one line logging 3.

javascript
console.log(document.getElementsByClassName("tagged").length);

You should see one line logging 1.

javascript
console.log(document.getElementsByClassName("tagged")[0].innerText);

You should see one line logging Tagged.


Missing elements return null

Always guard lookups that might fail when markup or feature flags differ between pages:

javascript
console.log(document.getElementById("nope") === null);

You should see one line logging true.

javascript
console.log(document.querySelector("#nope") === null);

You should see one line logging true.


Where to go next

For deeper selector practice, styling nodes after you fetch them, and more querySelectorAll patterns, see JavaScript DOM selector.


Summary

JavaScript get element and javascript get element by id questions map cleanly onto document.getElementById for id strings, querySelector / querySelectorAll for CSS selectors, and getElementsByTagName / getElementsByClassName when you want live HTMLCollection lists. The FAQ that burns beginners is what happens when a node is missing—both getElementById and querySelector return null, so you must guard before reading .style or .innerText.

Another recurring question is whether querySelectorAll is live like getElementsByClassName; it returns a static NodeList, so snapshots do not update when the DOM mutates. Scope selectors to a subtree when you already hold a parent element, and graduate to the broader JavaScript DOM selector article when class lists and combinators get complex.


References

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …