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.