foobarbarfoo
foobarbarfoo

Reputation: 369

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 = 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

Answers (4)

Tgr
Tgr

Reputation: 28200

$foo.is('html')

You seem to be reimplementing parents(), though.

Upvotes: 3

user113716
user113716

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

Ender
Ender

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

djdd87
djdd87

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

Related Questions