Skip to content

The Selectors API: querySelector and querySelectorAll

New Course Coming Soon:

Get Really Good at Git

Access DOM elements using querySelector and querySelectorAll. They accept any CSS selector, so you are no longer limited by selecting elements by `id`

Introduction

jQuery and other DOM libraries got a huge popularity boost in the past, among 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:

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.

These are all valid selectors:

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')
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my DOM Tutorial on The Valley of Code
→ Read my Browser Events Tutorial on The Valley of Code
→ Read my Browser APIs Tutorials on The Valley of Code

Here is how can I help you: