JAVASCRIPT
Find Nearest Ancestor with Specific Selector Using `closest()`
Learn how to efficiently traverse the DOM upwards to find the closest ancestor element that matches a given CSS selector, simplifying common UI interactions and data retrieval.
function findAncestor(startElement, selector) {
if (!(startElement instanceof Element)) {
console.error('The first argument must be an HTMLElement.');
return null;
}
return startElement.closest(selector);
}
// Example Usage:
// HTML:
// <div class="card">
// <h2 class="card-title">Product</h2>
// <p class="card-description">A description.</p>
// <button class="buy-button">Buy</button>
// </div>
//
// const buyButton = document.querySelector('.buy-button');
// const cardElement = findAncestor(buyButton, '.card');
// console.log(cardElement); // Logs the div.card element
//
// const titleElement = document.querySelector('.card-title');
// const anotherCard = findAncestor(titleElement, 'div');
// console.log(anotherCard); // Logs the div.card element
How it works: The `Element.closest()` method is incredibly useful for efficient DOM traversal, allowing you to find the nearest ancestor element (including itself) that matches a specified CSS selector. This snippet demonstrates how to leverage `closest()` to quickly locate a relevant parent from a deeply nested child element. This is often used in event handlers where `event.target` might be a small part of a larger component, and you need to access the main component element to extract data or perform an action.