Created
March 8, 2012 19:48
-
-
Save joedougherty/2002965 to your computer and use it in GitHub Desktop.
Ascend the DOM in jQuery with succinct notation
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
/* | |
I found myself needing to traverse the DOM tree upward more than just a few levels in a recent project (mostly due to heavy element nesting). | |
This function takes two arguments: the element in question and the number of levels to ascend. | |
Finally, it returns the element that's n levels above the initial element. | |
Ex: $(this).parent().parent().parent().parent().parent() could be more concisely expressed as ascendDOMLevels($(this), 5). | |
*/ | |
// Iterative version | |
function ascendDOMLevels( element, numOfLevels ) { | |
for (var i=0; i<numOfLevels; i++) { | |
var element = element.parent(); | |
} | |
return element; | |
} | |
// Recursive version | |
function ascendDOMLevels_recur( element, numOfLevels ) { | |
if (numOfLevels === 0) { | |
return element; | |
} else { | |
var element = element.parent(); | |
return ascendDOMLevels_recur( element, numOfLevels-1 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment