Created
December 18, 2014 23:31
-
-
Save brandonjp/d0a7f0c92768824843f1 to your computer and use it in GitHub Desktop.
jQuery prevOrAunt() - select previous siblings or parent previous siblings
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
// find first matching prev sibling of this or of parents, within 3 levels up | |
$form.prevOrAunt('.form-title,.panel-title,.panel-heading,:header', 3); | |
(function($) { | |
$.fn.prevOrAunt = function(search, optionalLimit) { | |
// prevOrAunt(search,optionalLimit) - searches only prev and aunts [Note: aunt=parent.prev, uncle=parent.next] | |
// search for matches in priority: prev siblings, parent prev siblings (repeat) | |
// with optional number limit for how far up the tree to search (or false to disable limit) | |
// * Modified from @Loren - http://stackoverflow.com/a/26237214/264601 | |
// Set a default number, attempt to user given limit | |
var defaultLimit = 99; // consider performance here | |
var isNumber = (Number(optionalLimit) === optionalLimit && optionalLimit % 1 === 0); | |
var limit = (isNumber && optionalLimit < defaultLimit) ? optionalLimit : defaultLimit; | |
// If limit is explicitly overridden with boolean=false, disable the limit, else use limit | |
var useLimit = (optionalLimit === false); | |
// Get the current element's siblings | |
var siblings = this.prevAll(search); | |
// If there's a match, we're done | |
if (siblings.length) return siblings.eq(0); | |
// Else traverse up another level | |
var parent = this.parent(); | |
// If we've reached our parental limit, body or no parent, return siblings (empty jQuery object) | |
if ((useLimit && limit-- && limit < 1) || parent === undefined || !parent.length || parent.get(0).tagName.toLowerCase() == 'body') return siblings; | |
// Else if we've not reached our limit try, try again | |
return parent.prevOrAunt(search); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment