Skip to content

Instantly share code, notes, and snippets.

@joedougherty
Created March 8, 2012 19:48
Show Gist options
  • Save joedougherty/2002965 to your computer and use it in GitHub Desktop.
Save joedougherty/2002965 to your computer and use it in GitHub Desktop.
Ascend the DOM in jQuery with succinct notation
/*
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