Fastest way to find the body tag via jQuery Fastest way to find the body tag via jQuery jquery jquery

Fastest way to find the body tag via jQuery


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


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;}


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