Explain Codes LogoExplain Codes Logo

In querySelector: how to get the first and get the last elements? What traversal order is used in the dom?

javascript
dom-traversal
javascript-queries
node-list
Nikita BarsukovbyNikita Barsukov·Feb 24, 2025
TLDR

Need the first match? Use: document.querySelector('.your-class'). Hunting for the last? Add :last-of-type: document.querySelector('.your-class:last-of-type'). The DOM is scanned from top to bottom, snagging the first or last child that matches your query.

Quick how-to:

  • First: document.querySelector('.item')
  • Last: document.querySelector('.item:last-of-type')

Let's take a deeper dive into the DOM's fascinating world and get acquainted with brilliant techniques like querySelectorAll and array methods.

Conquering all with querySelectorAll

querySelectorAll grants an amazing power to hunt all matches, returning a NodeList. But beware, it's an elaborate disguise! NodeList isn't an Array but fear not, the transformation is a piece of cake with Array.from() or spread syntax. The first element, obediently responds to index [0]. The last? Well, here's where JavaScript shows its magic with .at(-1) or Array methods:

// Round up all the elements const elements = document.querySelectorAll('.your-class'); // The first one's simple const firstElement = elements[0]; // "My precious" - Gollum // Few ways to grab the last one const lastElement = Array.from(elements).pop(); // "I'll be back" – Terminator // Or let's get fancy in modern browsers const lastElement = elements.at(-1); // "Here's looking at you kid" - Casablanca

Node properties to the rescue

Direct child access in a specific node? node.firstElementChild and node.lastElementChild got you covered, no need to tango with NodeLists and Arrays:

const firstChild = parent.firstElementChild; // Parent: "You're my favorite." const lastChild = parent.lastElementChild; // Parent: "Don't tell the others."

This efficient pair uphold the honor of DOM's depth-first traversal order with style.

Tag teaming with loops

When your div is overrun with multiple matching elements it's time to call for backup: loops!

const parentDiv = document.querySelector('.parent-div'); [...parentDiv.querySelectorAll('.child-class')].forEach((child, index, array) => { if (index === 0) // "The journey of a thousand miles begins with one step." - Lao Tzu if (index === array.length - 1) // "I am Iron Man." - Tony Stark // Far more quotes to choose from for the ones in the middle });

Dazzling with destructuring

const [first, ...rest, last] = Array.from(document.querySelectorAll('.your-class')); // "To infinity...and beyond!" - Buzz Lightyear

This ES6+ trick is not just a pretty face; it's an incredibly useful technique.

DOM Traversal: A front to back expedition

DOM isn’t messing around when it comes to traversal. The DOM uses pre-order depth-first search, an algorithm that digs as deep as it can go before climbing back out and moving on.

Watch out for browser support

While these methods are widely accepted, remember that older browsers may play truant. For example, the NodeList method .forEach() might require a polyfill to maintain harmony.

Selectors: The Dos and Don'ts

Though tempting, pseudo-classes like :first and :last are not universally accepted and we advise refraining from using them with querySelector or querySelectorAll. Tried and tested options like :first-child, :last-child, and :last-of-type are your best bet.