Created
April 27, 2011 20:56
-
-
Save carpeliam/945190 to your computer and use it in GitHub Desktop.
jQuery function to find the closest element somewhere above the current element.. so either a prev sibling or a parent or a parent's prev sibling.
This file contains hidden or 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
$.fn.nearest = function(selector) { | |
// base case if we can't find anything | |
if (this.length == 0) | |
return this; | |
var nearestSibling = this.prevAll(selector + ':first'); | |
if (nearestSibling.length > 0) | |
return nearestSibling; | |
return this.parent().nearest(selector); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An example usage:
And the jQuery:
As far as I can tell, without the above
.nearest()
, there's no single method that'd fill both divs with "You found me!". Am I wrong?