Reputation: 369
Let's say I'm writing a jQuery extension method. This method should climb the ancestor tree of an element until it reaches the document's root <html>
tag, at which point it should stop. I've implemented this as shown here:
$.fn.foo = function() {
var $foo = this;
while($foo[0] !== $(document).children()[0]) {
// do stuff with $foo
$foo = $foo.parent();
}
// do stuff
};
My question is: is there a better way than $foo[0] !== $(document).children()[0]
to know whether I've reached the root <html>
tag?
Upvotes: 3
Views: 746
Reputation: 322542
This should stop at HTML
.
$foo.parents().andSelf().each(function() {
// do something
console.log(this.nodeName);
});
Or if you're running the same jQuery method(s) against each node, do this:
$foo.parents().andSelf().someJQueryMethod();
Upvotes: 1
Reputation: 15221
What about this?
$.fn.foo = function() {
var $foo = this;
while($foo[0].tagName != 'HTML') {
// do stuff with $foo
$foo = $foo.parent();
}
// do stuff
};
Alternatively, if you don't actually need to traverse up, but only want to do things to all ancestors of a given node, you could use .parents() like so:
$.fn.foo = function() {
var $foo = this;
$foo.parents().andSelf().each(function() {
// do stuff with $foo
});
// do stuff
};
Upvotes: 1
Reputation: 68506
Don't compare against the first child, just see if a parent is returned:
var $foo = $(this);
while($foo.parent().length > 0) {
// do stuff with $foo
$foo = $foo.parent();
}
Here's a working fiddle.
Upvotes: 3