The DOM: Selectors API

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Introduction

jQuery and other DOM libraries got a huge popularity boost in the past, along with the other features they provided, thanks to an easy way to select elements on a page.

Traditionally browsers provided just a single way to select a DOM element - by its id attribute, with getElementById(), a method offered by the document object.

The Selectors API

Since 2013 the Selectors API, the DOM allows you to use two more useful methods:

  • document.querySelector()
  • document.querySelectorAll()

They can be safely used, as caniuse.com tells us, and they are even fully supported on IE9 in addition to all the other modern browsers, so there is no reason to avoid them, unless you need to support IE8 (which has partial support) and below.

They accept any CSS selector, so you are no longer limited by selecting elements by id.

  • document.querySelector() returns a single element, the first found
  • document.querySelectorAll() returns all the elements, wrapped in a NodeList object.

These are all valid selectors:

  • document.querySelector('#test')
  • document.querySelector('.my-class')
  • document.querySelector('#test .my-class')
  • document.querySelector('a:hover')

Basic jQuery to DOM API examples

Here below is a translation of the popular jQuery API into native DOM API calls.

Select by id

$('#test')
document.querySelector('#test')

We use querySelector since an id is unique in the page

Select by class

$('.test')
document.querySelectorAll('.test')

Select by tag name

$('div')
document.querySelectorAll('div')

More advanced jQuery to DOM API examples

Select multiple items

$('div, span')
document.querySelectorAll('div, span')

Select by HTML attribute value

$('[data-example="test"]')
document.querySelectorAll('[data-example="test"]')

Select by CSS pseudo class

$(':nth-child(4n)')
document.querySelectorAll(':nth-child(4n)')

Select the descendants of an element

For example all li elements under #test:

$('#test li')
document.querySelectorAll('#test li')

Lessons in this unit:

0: Introduction
1: The `window` object
2: The `document` object
3: Types of nodes
4: Traversing the DOM
5: Editing the DOM
6: ▶︎ Selectors API
7: DOM Ready
8: Add a class to an element
9: Remove a class from an element
10: Check if element has a class
11: Change a DOM node value
12: Loop through DOM elements
13: Add an image to the DOM
14: Create a DOM attribute
15: Remove children elements
16: Replace a DOM element
17: insertAdjacentHTML
18: Add click events to a list