In querySelector: how to get the first and get the last elements? What traversal order is used in the dom?
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:
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:
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!
Dazzling with destructuring
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.
Was this article helpful?