element.closest(selector) answers a question event handlers ask all the time: "which card, row or menu item was this click inside?" It starts at the element itself and goes up through its ancestors until one matches the selector. With one listener on a whole list, event.target.closest("li") finds the item that was clicked, whatever was clicked inside it.
Write closest(element, selector) in closest.js. It returns the same element element.closest(selector) would, without calling it.
The search starts with element itself: if it matches, it is the answer.
Otherwise each ancestor is tested in order, nearest first, and the first match is returned.
When nothing on the way up matches, the result is null.
The search goes up to the <html> element and stops there: the document is never returned.
Selectors are matched as the browser matches them, including combinators that look above the element ("main p"), attributes, pseudo-classes and selector lists.
A tree that is not in the document is searched up to its own top element.
Inside a shadow tree, the search stops at the top of that tree, as the built-in does: it never reaches the host element.
An invalid selector throws a SyntaxError, even when the element has no parent.
It works for very deep trees, and when Element.prototype.closest does not exist.
constcard= document.createElement("article");card.className ="card";card.innerHTML ="<p><span>x</span></p>";closest(card.querySelector("span"), ".card"); // card, though it is not in the pageclosest(card.querySelector("span"), "body"); // null
JAVASCRIPT
closest(document.body, "p[["); // throws a SyntaxError (a DOMException)