Created
April 29, 2017 11:05
-
-
Save yairEO/c5f85be5bf7f583f3d5eaf3dce1a5287 to your computer and use it in GitHub Desktop.
jQuery plugin - find closest (inside / outside)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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