Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does $("body") use Sizzle Engine?

I understand that $("#id") is faster because it maps to a native javascript method. Is the same true of $("body")?

like image 739
Matrym Avatar asked Dec 06 '22 00:12

Matrym


2 Answers

No it does not use Sizzle, there's a special shortcut for $("body") in place, you can see the code here:

    // The body element only exists once, optimize finding it
    if ( selector === "body" && !context && document.body ) {
        this.context = document;
        this[0] = document.body;
        this.selector = "body";
        this.length = 1;
        return this;
    }

Note that this isn't quite the same as $(document.body), as the resulting context of $("body") is document, where as $(document.body) (like any other DOM node) has a context of itself.

like image 179
Nick Craver Avatar answered Dec 29 '22 06:12

Nick Craver


This is straight from the source (code):

if ( selector === "body" && !context && document.body ) {
    this.context = document;
    this[0] = document.body;
    this.selector = "body";
    this.length = 1;
    return this;
}

For tags other than body

If you dig a little deeper it turns out they will use getElementsByTagName if no context is given. This will give a nice boost to performance over using the Sizzle engine.

// HANDLE: $("TAG")
} else if ( !context && !rnonword.test( selector ) ) {
    this.selector = selector;
    this.context = document;
    selector = document.getElementsByTagName( selector );
    return jQuery.merge( this, selector );

// HANDLE: $(expr, $(...))
}
like image 44
ChaosPandion Avatar answered Dec 29 '22 04:12

ChaosPandion