Web APIs
Element.closest()
Returns the element itself or its nearest matching ancestor, or null if none matches.
Formal Syntax & Structure
javascript syntaxjavascript
element.closest(selectors)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| selectors | string | Valid CSS selector list. |
Return Value
Element | null
Nearest matching element or null.
Working Example
Example Snippetjavascript
const list=document.createElement("div"),b=document.createElement("button"),s=document.createElement("span");b.dataset.action="save";b.append(s);list.append(b);list.addEventListener("click",e=>{const hit=e.target instanceof Element?e.target.closest("button[data-action]"):null;if(hit&&list.contains(hit))console.log(hit.dataset.action);});s.click();