Reputation: 75844
How do I traverse ancestors with jQuery?
The current code is getting stuck in a recursive loop:
HTML:
<html>
<body>
<div>
<ul>
<li></li>
</ul>
</div>
</body>
</html>
JS:
function traverse($node){
while ( $node.get(0) !== $("html").get(0) ) {
console.log($node);
traverse($node.parent());
}
}
//traverse($("ul li"));
To observe the problem, un-comment the last line, but be warned that it may freeze your browser.
The same on JSFiddle: http://jsfiddle.net/WpvJN/1/
Upvotes: 1
Views: 173
Reputation: 147523
I expect you need to put a limit on the traverse in case the parent you seek is not an ancestor of where you started. Otherwise, you either end up in an endless loop or run out of parents.
For example, a generic function to go from an element up to a parent with a particular tag name, you might do (not jQuery but I'm sure you can convert it if necessary):
function upTo(tagName, el) {
tagName = tagName.toLowerCase();
// Make sure el is defined on each loop
while (el && el.tagName && el.tagName.toLowerCase() != tagName) {
el = el.parentNode;
}
return el;
}
An alternative is to check for el.parentNode
and stop when there are no more.
There is always an HTML node in an HTML document, so as long as you don't start from the document node, you'll always get there.
Upvotes: 0
Reputation: 123563
You can get the collection with .parents()
and iterate with .each()
:
$('ul li').parents().each(function () {
console.log(this);
});
Upvotes: 5