Script Valley
JavaScript in the Browser: DOM, Events & APIs
Understanding the DOMLesson 1.2

How to select DOM elements with querySelector

querySelector, querySelectorAll, getElementById, CSS selector syntax, null returns, NodeList vs HTMLCollection

Selecting DOM Elements

The two most versatile selection methods are querySelector and querySelectorAll. Both accept any valid CSS selector string.

// Single element — returns first match or null
const btn = document.querySelector('#submit-btn');
const heading = document.querySelector('h1');
const active = document.querySelector('.card.active');

// All matches — returns a static NodeList
const items = document.querySelectorAll('ul li');

NodeList Is Not an Array

A NodeList looks like an array but lacks most array methods. Convert it when you need map, filter, or reduce.

const items = document.querySelectorAll('.item');
const texts = Array.from(items).map(el => el.textContent);

Faster Lookups by ID

getElementById is marginally faster for ID lookups because it skips CSS parsing.

const modal = document.getElementById('modal'); // no # prefix

Always check for null before accessing properties. If a selector matches nothing, querySelector returns null and any property access on it throws a TypeError.

const el = document.querySelector('.missing');
if (el) el.textContent = 'Found it';

Up next

Reading and writing element properties in the DOM

Sign in to track progress