jQuery: Determine if jQuery object is root html tag
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 = th开发者_运维技巧is;
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?
$foo.is('html')
You seem to be reimplementing parents(), though.
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.
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
};
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();
- http://api.jquery.com/parents/
- http://api.jquery.com/andself/
精彩评论