Skip to content

Instantly share code, notes, and snippets.

@subhog
Last active August 29, 2015 13:57
Show Gist options
  • Save subhog/9616619 to your computer and use it in GitHub Desktop.
Save subhog/9616619 to your computer and use it in GitHub Desktop.
Find next (or previous) matching element in the DOM, wherever it is in the tree.
(function($) {
var getNext = function(item) {
if(item.length === 0) return null;
if(item.next().length > 0) return item.next();
return getNext(item.parent());
};
var getPrev = function(item) {
if(item.length === 0) return null;
if(item.prev().length > 0) return item.prev();
return getPrev(item.parent());
};
$.fn.nextAnywhere = function(selector) {
var next = getNext(this);
while(next && next.length > 0) {
if(next.is(selector)) return next;
var el = next.find(selector);
if(el.length > 0) return el.first();
next = getNext(next);
}
return null;
};
$.fn.prevAnywhere = function(selector) {
var prev = getPrev(this);
while(prev && prev.length > 0) {
if(prev.is(selector)) return prev;
var el = prev.find(selector);
if(el.length > 0) return el.last();
prev = getPrev(prev);
}
return null;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment