JQuery: determine if jQuery object is html root tag

Say I'm writing a jQuery extension method. This method should climb the ancestor tree of the element until it reaches the <html>document root tag , after which it should stop. I implemented this as shown below:

$.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]knowing if I have reached the root tag <html>?

+3
source share
4 answers
$foo.is('html')

It looks like you are reorienting your parents () .

+3
source

Do not compare with the first child, just see if the parent returns:

var $foo = $(this);

while($foo.parent().length > 0) {
    // do stuff with $foo
    $foo = $foo.parent();
}

Here's a working fiddle .

+3

?

$.fn.foo = function() {

    var $foo = this;

    while($foo[0].tagName != 'HTML') {
        // do stuff with $foo
        $foo = $foo.parent();
    }

    // do stuff

};

, , node, .parents() :

$.fn.foo = function() {

    var $foo = this;

    $foo.parents().andSelf().each(function() {
        // do stuff with $foo
    });

    // do stuff

};
+1
source

This should stop at HTML.

​$foo.parents().andSelf().each(function() {
    // do something
    console.log(this.nodeName);
});​​​

Or, if you use the same jQuery method for each node, do the following:

$foo.parents().andSelf().someJQueryMethod();
+1
source

Source: https://habr.com/ru/post/1763176/


All Articles