Skip to main content

Selectors for working with DOM elements

DOM selectors are ways to find elements on a page using JavaScript. Without them it is impossible to interact with HTML - you first need to get the element to do anything with it (change its text, style, remove it, add an event handler, and so on).

1. What a "selector" is

A selector is a way to specify which element in the DOM to select. It can be:

  • by id,
  • by tag,
  • by class,
  • by attribute,
  • or through a CSS selector.

2. Main methods for selecting elements

MethodReturnsTakesExample
getElementById(id)one elementid (without #)document.getElementById("header")
getElementsByClassName(class)HTMLCollection (array-like)class name (without .)document.getElementsByClassName("menu")
getElementsByTagName(tag)HTMLCollectiontag namedocument.getElementsByTagName("p")
querySelector(selector)first elementCSS selectordocument.querySelector(".menu li")
querySelectorAll(selector)NodeList (all matching)CSS selectordocument.querySelectorAll("div > p")

3. Each one in detail

document.getElementById()

Finds one element by its id attribute.

javascript
<h1 id="title">Hello!</h1>
javascript
const el = document.getElementById("title"); console.log(el.textContent); // Hello!

Very fast. Works only by id. Returns only one element.

document.getElementsByClassName()

Finds all elements with the given class.

javascript
<p class="text">First</p> <p class="text">Second</p>
javascript
const els = document.getElementsByClassName("text"); console.log(els.length); // 2

Fast, supported everywhere. Returns an HTMLCollection (needs converting to an array to use forEach).

document.getElementsByTagName()

Finds all elements by tag.

javascript
const paragraphs = document.getElementsByTagName("p");

Returns a live collection - if a new <p> appears in the DOM, it gets added automatically.

document.querySelector()

Uses CSS selectors. Returns the first matching element.

javascript
const item = document.querySelector(".menu li.active");

Universal - supports all CSS selector capabilities. Returns only one element.

document.querySelectorAll()

Returns all elements matching the CSS selector.

javascript
const items = document.querySelectorAll(".menu li"); items.forEach(li => console.log(li.textContent));

Returns a NodeList, so forEach() can be used. Does not update automatically (unlike getElementsBy...).

4. Types of selectors (like in CSS)

SelectorExampleDescription
By tag"div"all <div>
By class".item"all elements with the .item class
By id"#header"the element with id="header"
By attribute"[type='text']"elements with type="text"
Descendants"ul li"all <li> inside <ul>
Direct children"ul > li"only those at one level of nesting
Combined"div.item.active"<div class="item active">
Pseudo-classes"li:first-child", "input:checked"specific states

5. When to use which

GoalBetter to use
Quickly get an element by idgetElementById()
Find by class or taggetElementsByClassName() / getElementsByTagName()
Complex lookup (like in CSS)querySelector() / querySelectorAll()
A collection that updates itselfgetElementsBy...
A one-time static listquerySelectorAll()

6. A complex lookup example:

HTML:

javascript
<div class="card"> <h2 class="title">Title</h2> <p class="desc">Description</p> </div>

JS:

javascript
const card = document.querySelector(".card"); const title = card.querySelector(".title"); const desc = card.querySelector(".desc"); console.log(title.textContent); // "Title"

7. Working with the found elements

Once an element is found, you can:

javascript
const el = document.querySelector("#myDiv"); el.textContent = "New text"; // change the content el.style.color = "red"; // change the style el.classList.add("active"); // add a class el.addEventListener("click", fn); // attach a handler

8. Useful tip:

  • Use querySelector / querySelectorAll - this is the universal, modern way (works with any CSS selectors).
  • The getElementById and getElementsByClassName methods are useful when you need maximum performance (for example, in legacy code or with thousands of elements).

Summary:

MethodReturnsFeatures
getElementById(id)one elementfast, unique id
getElementsByClassName()HTMLCollectiondynamic collection
getElementsByTagName()HTMLCollectionby tag
querySelector()first elementCSS selector
querySelectorAll()NodeListall matching elements

In short: DOM selectors are tools for finding elements on a page.

Simple ones (getElementById) are fast. Modern ones (querySelector) are flexible and powerful.

Use CSS selectors when you need to pinpoint an element precisely, and simple methods when speed and readability matter.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.