jQuery find nearest
Asked Answered
M

1

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

Majestic answered 1/11, 2011 at 23:0 Comment(3)
What is your definition of "nearest"?Ozoniferous
Great!to make it compatible with the standard return types of such jquery functions, we better change the second line from var o = {}; to var o = [];Blastema
Actually, I think o = $(); would be better for compatibility.Mailer
Y
4

Have you considered jQuery .closest()?

Yeargain answered 1/11, 2011 at 23:1 Comment(1)
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. ChrisMajestic

© 2022 - 2024 — McMap. All rights reserved.