Last active
August 29, 2015 13:57
-
-
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.
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
(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