Home » Html » Fastest way to find the body tag via jQuery

Fastest way to find the body tag via jQuery

Posted by: admin November 30, 2017 Leave a comment

Questions:

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')
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

Questions:
Answers:

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

Questions:
Answers:

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