Selecting elements on a page

Every DOM program starts by finding an element, and the page offers four ways to do it: an id, a CSS selector, a walk up from the element you already have, and a test of whether an element matches a selector. The first two search the document, the last two work on the path between an element and its ancestors.

The four programs of this lesson run on the same small shop page and answer one question each: which element does a lookup return, what does a list of matches hold, how does a handler find the item around a button, and which selectors can express a condition. All of them run in jsdom, set up as the previous lesson showed, and print text so the output is the same on every run.

An id and a document

getElementById is the fastest lookup on a page, because the parser keeps a map from an id to its element. The method belongs to the document and to no element, the id is compared as a case-sensitive string, and a page that has no such id gives null rather than an empty element. A program that reads a property of the result without checking it is one missing element away from an error.

The program reads the heading twice, once by id and once by selector, and prints what a missing id gives.

The file byid.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<html><body>', '<h1 id="title">Shop</h1>', '<p id="lead">three items, one of them sold</p>', '<ul class="items">', '<li class="item" data-id="1"><a href="/one">one</a></li>', '<li class="item" data-id="2"><a href="/two">two</a></li>', '<li class="item sold" data-id="3"><a href="/three">three</a></li>', '</ul>', '</body></html>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/shop' }); const { document } = dom.window; const title = document.getElementById('title'); console.log('the heading:', title.textContent); console.log('the same node from querySelector:', document.querySelector('#title') === title); console.log('a missing id gives null:', document.getElementById('missing')); console.log('ids are case-sensitive:', document.getElementById('Title')); console.log('the node type and the tag:', title.nodeType, title.tagName);

node byid.js

the heading: Shop
the same node from querySelector: true
a missing id gives null: null
ids are case-sensitive: null
the node type and the tag: 1 H1

The two lookups found the same object, which is the rule of the DOM: one element, one node, however many ways a program reaches it. The node type is a number, one for an element, and the tag name is uppercase here even though the fixture wrote it in lowercase. That last detail is what a comparison against a tag name has to allow for.

querySelector and querySelectorAll

querySelector takes any CSS selector and returns the first element in document order, or null. querySelectorAll returns every match as a NodeList: a static list with length, indexing and forEach, but no map and no filter. A program that wants an array calls Array.from or spreads the list, and the copy is what the array methods need.

The program counts the items, walks the list with its own index, and turns the links into an array of strings.

The file query.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<html><body>', '<h1 id="title">Shop</h1>', '<ul class="items">', '<li class="item" data-id="1"><a href="/one">one</a></li>', '<li class="item" data-id="2"><a href="/two">two</a></li>', '<li class="item sold" data-id="3"><a href="/three">three</a></li>', '</ul>', '</body></html>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/shop' }); const { document } = dom.window; const items = document.querySelectorAll('.item'); console.log('how many items:', items.length); console.log('the first one:', document.querySelector('.item').textContent); console.log('a NodeList has forEach:', typeof items.forEach); items.forEach((item, index) => { console.log(index, item.getAttribute('data-id'), item.textContent); }); const links = document.querySelectorAll('.item a'); console.log('every link:', Array.from(links).map((link) => link.textContent).join(', ')); console.log('spread works too:', [...links].length); console.log('a selector with no match:', document.querySelectorAll('.sale').length); console.log('querySelector of a missing class:', document.querySelector('.sale'));

node query.js

how many items: 3
the first one: one
a NodeList has forEach: function
0 1 one
1 2 two
2 3 three
every link: one, two, three
spread works too: 3
a selector with no match: 0
querySelector of a missing class: null

The single lookup gives the first match and the plural one gives a list, and the difference between the null and the zero is the difference between a question about one element and a question about all of them. The list was taken before anything changed on the page, so it is a photograph and not a window onto the document: an element added later is not in it.

closest and matches

closest starts at the element itself and walks up until a selector matches, and matches asks whether the element itself matches without moving. Both take the same selectors as the document lookups. In a handler the target of a click is often the text or the icon inside a button, and closest is how the handler finds the element the page cares about; the lesson on events builds on it.

The program has one link inside one item and walks up from the link, which is the move a click handler makes in the other direction.

The file closest.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<html><body>', '<ul class="items">', '<li class="item" data-id="1"><a href="/one">one</a></li>', '<li class="item sold" data-id="3"><a href="/three">three</a></li>', '</ul>', '</body></html>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/shop' }); const { document } = dom.window; const link = document.querySelector('.item a'); console.log('the link:', link.textContent); console.log('the item around it:', link.closest('li').getAttribute('data-id')); console.log('is that item sold:', link.closest('.sold') !== null); console.log('closest starts at the element itself:', link.closest('a') === link); console.log('the list around it:', link.closest('ul').className); console.log('matches on the link:', link.matches('.item a'), link.matches('.sold a')); console.log('matches on the item:', link.closest('li').matches('.sold'));

node closest.js

the link: one
the item around it: 1
is that item sold: false
closest starts at the element itself: true
the list around it: items
matches on the link: true false
matches on the item: false

The two selectors on the link ask about the whole path and not only about the element: the link is inside an item, so .item a matches it, while .sold a does not, because the ancestor of this link is not sold. The last line moves the question to the item and gets the other answer, which is exactly what a handler does when it has to know whether the row it was clicked in is a special one.

Attributes and positions

A selector is a small language, and four of its forms do most of the work on a page: a class with a dot, two classes written together, an attribute in brackets, and a position such as :nth-child or :not. An attribute selector compares a value as a string, so a quoted value is the safe form. The last program also reads a property of a missing element, which is the error every program that skips a null check runs into.

The program asks six questions of the same list and prints the answers, then reads the text of a selector that matches nothing.

The file selectors.js:

const { JSDOM } = require('jsdom'); const html = [ '<!doctype html>', '<html><body>', '<ul class="items">', '<li class="item" data-id="1"><a href="/one">one</a></li>', '<li class="item" data-id="2"><a href="/two">two</a></li>', '<li class="item sold" data-id="3"><a href="/three">three</a></li>', '</ul>', '</body></html>', ].join(''); const dom = new JSDOM(html, { url: 'http://localhost/shop' }); const { document } = dom.window; console.log('by attribute:', document.querySelector('[data-id="2"]').textContent); console.log('two classes together:', document.querySelectorAll('.item.sold').length); console.log('the second child:', document.querySelector('li:nth-child(2)').getAttribute('data-id')); console.log('the items that are not sold:', document.querySelectorAll('li:not(.sold)').length); console.log('an attribute prefix:', document.querySelectorAll('[data-id^="1"]').length); console.log('the sold item has its own class:', document.querySelector('a[href="/three"]').closest('li').className); const missing = document.querySelector('.sale'); try { console.log(missing.textContent); } catch (error) { console.log('the error:', error.name, '-', error.message); }

node selectors.js

by attribute: two
two classes together: 1
the second child: 2
the items that are not sold: 2
an attribute prefix: 1
the sold item has its own class: item sold
the error: TypeError - Cannot read properties of null (reading 'textContent')

Every question was answered by a selector and a count, and the last two lines are the shape of a bug: a selector that matches nothing returns null, and the property read on the next line throws. The check is one line, if (missing === null), and it is the reason the handlers later in this part start with a guard.

Exercises

  1. Count the links inside the list with one selector. How many elements does querySelectorAll find without a class in the selector?
  2. Take the list into an array with Array.from and sort the titles backwards with map and sort. Which method does the NodeList itself not have?
  3. Print document.querySelectorAll('li').length, then append an item and print it again. Why is the number the same, and which method gives a live list instead?
  4. Ask for the fourth item with li:nth-child(4). What does the program get, and what is the shortest way to find out whether the list has one?
  5. Walk up from a link to the body with closest. Where does the walk stop when no ancestor matches?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which method returns the first element that matches a selector?

    Answer

    querySelector

    The plural method returns every match in a NodeList, and the other two look for an id and an ancestor.

  2. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li>one</li><li>two</li><li>three</li></ul>", { url: "http://localhost/" }); console.log(dom.window.document.querySelectorAll("li").length);

    Answer

    3

    The selector matches every list item, and the list knows its own length.

  3. What does querySelector give when nothing matches?

    Answer

    null

    A single lookup has no empty list to return, so null is the answer and the caller has to check it.

  4. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li data-id=2><a href=/two>two</a></li></ul>", { url: "http://localhost/" }); const link = dom.window.document.querySelector("a"); console.log(link.closest("li").getAttribute("data-id"));

    Answer

    2

    closest walks up from the link to the first list item, and the id comes from its attribute.

  5. What does a NodeList from querySelectorAll hold?

    Answer

    A snapshot of the matches at the moment of the call

    The list is static, so an element added later is not in a list taken before the change.

  6. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li>one</li><li>two</li></ul>", { url: "http://localhost/" }); const document = dom.window.document; const items = document.querySelectorAll("li"); document.querySelector("ul").append(document.createElement("li")); console.log(items.length);

    Answer

    2

    The NodeList was taken before the append, and a static list does not see a later element.

  7. What does matches ask?

    Answer

    Whether the element itself matches a selector

    matches stays on the element, while closest is the method that moves up the tree.

  8. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<ul><li data-state=open>one</li><li data-state=open>two</li><li>three</li></ul>", { url: "http://localhost/" }); console.log(dom.window.document.querySelectorAll("[data-state]").length);

    Answer

    2

    The attribute selector matches the elements that carry the attribute, whatever its value.

  9. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>one</p>", { url: "http://localhost/" }); console.log(dom.window.document.querySelector(".sale"));

    Answer

    null

    Nothing on the page carries the class, so the single lookup has no element to return.

  10. What does this program print? const { JSDOM } = require("jsdom"); const dom = new JSDOM("<h1 id=title>Shop</h1><p>a page</p>", { url: "http://localhost/" }); console.log(dom.window.document.getElementById("title").nodeType);

    Answer

    1

    The node type of every element is one, while the document itself is nine and a tag name is text.

The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev