Find parent with class.
TODO: collapasable, copyable, download, etc
In JS for an event.target, how can I look at that element and search it's parents to see if one of them has a css class of air-datepicker
?In JavaScript, to check if an element's parent has a specific CSS class, you can use the closest
method. This method travels up the DOM tree from the current element and returns the first element that matches a given selector. If no such element exists, it returns null
.
For your specific case, where you're looking to see if any of the parent elements of an event target has a CSS class of air-datepicker
, you can do something like this:
// Assuming `event` is the event object you're working with
const hasAirDatepickerParent = event.target.closest('.air-datepicker');
if (hasAirDatepickerParent) {
console.log('Found a parent with the "air-datepicker" class!', hasAirDatepickerParent);
} else {
console.log('No parent with the "air-datepicker" class found.');
}
Here's a breakdown of how this works:
event.target
is the element that triggered the event.closest('.air-datepicker')
searches for the nearest parent element (including the target itself) that has theair-datepicker
class. The search includes the element itself and traverses up through its ancestors in the DOM tree.- If such an element is found,
closest
returns it, otherwise, it returnsnull
. - You can then use an
if
statement to check if the result is truthy (an element was found) or falsy (null
, meaning no such parent exists), and perform actions accordingly.
Related Chats
Prevent Event Propagation with JS 0.369
Merge and Deduplicate Tailwind Classes 0.357
Modern ES6 Array Filtering 0.339
Dismiss Pop-up on Click 0.338
Check for Not Null 0.321
Equalize Heights Dynamically JavaScript 0.318
JavaScript to TypeScript Transition 0.310