Skip to content

Instantly share code, notes, and snippets.

@JenkinsDev
Created March 13, 2015 18:27
Show Gist options
  • Save JenkinsDev/56f9709b536cc91bc134 to your computer and use it in GitHub Desktop.
Save JenkinsDev/56f9709b536cc91bc134 to your computer and use it in GitHub Desktop.
Traverse To Ancestor ~ jQuery
<!DOCTYPE html>
<html>
<head>
<title>Example for traverseToAncestor</title>
</head>
<body>
<div class="top-ancestor">
<div class="grandparent">
<div class="parent">
<div class="child"></div>
</div>
</div>
</div>
</body>
<!-- Import yo JS files! -->
<script>
traverseToAncestor($('.child'), '.top-ancestor'));
// The above would return a jQuery instance for the element with the class top-ancestor.
</script>
</html>
/**
* Attempts to traverse through the DOM tree to find the specificed ancestor
* selector. If it doesn't find the ancestor within ``maxTraversalAmount``,
* default is 10, times then it returns null.
*
* @param dom: The jQuery DOM element to start at.
* @param parentSelector: The jQuery selector string syntax used to find the "ancestor"
* @param maxTraversalAmount: The maximum attempts to traverse the DOM tree.
*
* @returns jQuery DOM element or NULL.
*/
function traverseToAncestor(dom, parentSelector, maxTraversalAmount) {
var i = 1,
currentDomEle = dom,
idSelector = parentSelector.split("#")[1] || null,
clsSelector = parentSelector.split(".")[1] || null,
maxTraversalAmount = maxTraversalAmount || 10;
for (; i<=maxTraversalAmount; i++) {
currentDomEle = currentDomEle.parent();
if (currentDomEle.id === idSelector || currentDomEle.hasClass(clsSelector)) {
return currentDomEle;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment