Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created April 29, 2017 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/c5f85be5bf7f583f3d5eaf3dce1a5287 to your computer and use it in GitHub Desktop.
Save yairEO/c5f85be5bf7f583f3d5eaf3dce1a5287 to your computer and use it in GitHub Desktop.
jQuery plugin - find closest (inside / outside)
// http://stackoverflow.com/a/29823718/104380
jQuery.fn.findClosest = function (selector) {
// If we have a :this selector
var output = $(),
down = this.find(selector),
siblings,
recSearch,
foundCount = 0;
if(down.length) {
output = output.add(down);
foundCount += down.length;
}
// if all elements were found, return at this point
if( foundCount == this.length )
return output;
siblings = this.siblings(selector);
if( siblings.length) {
output = output.add(siblings);
foundCount += siblings.length;
}
// this is the expensive search path if there are still unfound elements
if(foundCount < this.length){
recSearch = rec(this.parent().parent());
if( recSearch )
output = output.add(recSearch);
}
function rec(elm){
var result = elm.find(selector);
if( result.length )
return result;
else
rec(elm.parent());
}
return output;
};
// Test case
var buttons = $('a').findClosest('button');
console.log(buttons);
buttons.click(function(){
this.style.outline = "1px solid red";
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment