JAVASCRIPT
Traversing Ancestors and Self with `closest()`
Discover how to efficiently traverse the DOM upwards from a given element to find the nearest ancestor (or itself) that matches a specified CSS selector using `element.closest()`.
function findNearestAncestor(element, selector) {
if (!(element instanceof Element)) {
console.error("Invalid element provided. Must be a DOM Element.");
return null;
}
return element.closest(selector);
}
// Example Usage:
// // Assume HTML structure like:
// // <div class="app">
// // <section class="section" id="products">
// // <div class="card" data-product="A1">
// // <h2 class="title">Product A</h2>
// // <p>Description</p>
// // <button class="add-to-cart-btn" data-id="a1">Add to Cart</button>
// // </div>
// // </section>
// // </div>
//
// const addToCartButton = document.querySelector('.add-to-cart-btn');
// if (addToCartButton) {
// // Find the nearest ancestor with class 'card'
// const productCard = findNearestAncestor(addToCartButton, '.card');
// if (productCard) {
// console.log("Found product card for button:", productCard.dataset.product); // Accessing data-product attribute
// }
//
// // Find the nearest ancestor with id 'products' (a section element)
// const productSection = findNearestAncestor(addToCartButton, '#products');
// if (productSection) {
// console.log("Found product section:", productSection.id);
// }
//
// // If the element itself matches the selector, it returns itself
// const sameButton = findNearestAncestor(addToCartButton, 'button');
// if (sameButton) {
// console.log("Found button itself:", sameButton.className);
// }
// }
How it works: This snippet showcases the `element.closest(selector)` method, which is highly useful for DOM traversal. It starts from the given `element` and walks up the DOM tree, including the element itself, until it finds an ancestor that matches the provided CSS `selector`. This is invaluable for scenarios like event delegation where you need to find a specific parent container from the `event.target`.