8

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

Christian
  • 81
  • 1
  • 2

1 Answers1

4

Have you considered jQuery .closest()?

James Hill
  • 60,353
  • 20
  • 145
  • 161
  • Well, I have a site where I have several checkboxes which is actually offers visitors can order. These offers are not unique and may be on several pages. Sometimes they are wraped in different html or labels. I needed to check the 'nearest' checkbox when clicked on a connecting label. Actually I wanted to check all, but only add a data object to one of them. Closest() only goes up the DOM, it will not find elemtents in f.e another td in the same table. Chris – Christian Nov 02 '11 at 10:19