Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find the body tag via jQuery

On every document ready I need to get the body tag via jQuery and I'm more curious about the answer to this than anything else.

Let's say this is the body tag on every page on my site:

<body id="body">

Is it faster to query the body tag by just the tag name:

$('body')

or query it by its id:

$('#body')
like image 473
adam Avatar asked Oct 09 '11 20:10

adam


3 Answers

The fastest way would be $(document.body).
This doesn't involve any selector parsing.

$('body') is much faster (in Firefox and Chrome) than $('#body').

Test

like image 170
SLaks Avatar answered Nov 11 '22 21:11

SLaks


jQuery optimises the finding of the body element. Here's the relevant jQuery source:

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

So using $("body") will be pretty much as fast as $(document.body), as suggested in other answers. Using $("body") will certainly be faster than giving the body an id, because if an id is used, the above, optimised code cannot run. jQuery will use getElementById, which is fast, but not as fast as the above!

Edit

As pointed out by @SLaks, $(document.body) is the fastest, which makes sense when you look at the jQuery source that will handle a DOM element selector, rather than a string:

if ( selector.nodeType ) {
    this.context = this[0] = selector;
    this.length = 1;
    return this;
}
like image 7
James Allardice Avatar answered Nov 11 '22 22:11

James Allardice


Tag name is the fastest in Chrome, and probably most browsers. Faster yet would be to skip the jQuery wrapper:

document.getElementsByTagName("body");

Or

document.body
like image 2
Jack Avatar answered Nov 11 '22 23:11

Jack