Created
December 18, 2014 23:33
-
-
Save brandonjp/023a4befaaf3f9908b21 to your computer and use it in GitHub Desktop.
jQuery prevParentPrev() - matches previous siblings, parent, parent prev (repeat)
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
// find first matching prev sibling, parent, or parent prev sibling, within 3 levels up | |
$form.prevParentPrev('.form-title,.panel-title,.panel-heading,:header') | |
(function($) { | |
$.fn.prevParentPrev = function(search, optionalLimit) { | |
// prevParentPrev(search,optionalLimit) - similar to prevOrAunt() but also searches parents | |
// search for matches in priority: prev siblings, parent, 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 previous 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(search); | |
// If there's a match, we're done | |
if (parent.length) return parent.eq(0); | |
// 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.prevParentPrev(search); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment