views:

56

answers:

4

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?

+2  A: 

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.

GenericTypeTea
+1  A: 

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

};
Ender
+1  A: 

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();
patrick dw
+3  A: 
$foo.is('html')

You seem to be reimplementing parents(), though.

Tgr