Skip to content

Instantly share code, notes, and snippets.

@carpeliam
Created April 27, 2011 20:56
Show Gist options
  • Save carpeliam/945190 to your computer and use it in GitHub Desktop.
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.
$.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);
};
@carpeliam
Copy link
Author

An example usage:

<div class="findme">...</div>
<a href="#" class="finder">Find me!</a>
<div class="findme">...</div>
<b><a href="#" class="finder">Find me!</a></b>

And the jQuery:

$('.finder').nearest('.findme').text('You found me!');

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment