Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find nearest

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

like image 532
Christian Avatar asked Nov 01 '11 23:11

Christian


People also ask

What is closest in jQuery?

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.

Is closest JavaScript or jQuery?

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.

How can I get next sibling in jQuery?

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.

How do you use nearest?

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.


1 Answers

Have you considered jQuery .closest()?

like image 199
James Hill Avatar answered Oct 04 '22 12:10

James Hill