Christian
Christian

Reputation: 81

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

Upvotes: 8

Views: 2824

Answers (1)

James Hill
James Hill

Reputation: 61793

Have you considered jQuery .closest()?

Upvotes: 4

Related Questions