How to get closest parent element in js/jquery

To get the nearest parent element in JavaScript or jQuery, you can use the following methods:

JavaScript:

In JavaScript, you can use the closest() method, which searches for the nearest ancestor element (or the element itself) that matches the given selector.

Example:

let element = document.querySelector('.child'); // select the element
let parent = element.closest('.parent'); // find the nearest parent element with class "parent"
console.log(parent);

jQuery:

In jQuery, there is also a closest() method that works similarly.

Example:

let parent = $('.child').closest('.parent'); // find the nearest parent element with class "parent"
console.log(parent);

The closest() method searches for the nearest element matching the selector, moving up the DOM tree.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to exclude posts with parent post in wp_query, WordPress

To exclude posts that have a parent (i.e., child posts) in a WP_Query request, you can use the post_parent argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0, which means that only top-level posts (posts without a parent) will be included in…
Read more