TIL: closest(selector) and matches(selector)

David Viramontes

David Viramontes
Did you know that you can use closest
to find an element's nearest ancestor that matches a specific selector (including the element itself, which it checks first)?
<article class="post">
<div class="content">
<h1 class="title">hello</h1>
<div class="cta">
<p>call to action</p>
<button id="button">click me</button>
</div>
</div>
</article>
const button = document.querySelector('#button')
// Find the nearest article ancestor
const article = button.closest('article')
// Find the nearest element with class 'content'
const content = button.closest('.content')
There is also matches for checking if an element matches a selector. This is useful for conditional logic based on element properties.
const button = document.querySelector("#button");
// Check if the button is inside an article
if (button.closest("article")?.matches(".post")) { ... }
// Check if the button itself has specific classes
if (button.matches(".cta button")) { ... }