I needed to find the nearest element, relative to another element. I wanted a generic function not locked to a spesific tree structure. Maybe it already exists within jQuery and if so please show me! Here is what I came up with and it works for what I needed:
$.fn.nearest = function(s) {
var o = {};
var p = $(this).parent();
while(p.length) {
if(p.find(s).length) {
o = p.find(s).first();
break;
}
else {
p = p.parent();
}
}
return o;
};
-Chris
The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
Definition and UsageThe closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.
Have you considered jQuery .closest()?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With