7

Which is the best way (performance-wise) to get the root document node (the <html> element) in jQuery? I can think of several methods that may or may not work:

$("html")

$(document.documentElement)

$(document) (?)

$.root (?)

$.document (?)

dalgard
  • 3,614
  • 2
  • 22
  • 28

3 Answers3

16

$(document.documentElement) is the fastest, by quite some margin (see tests here).

You can get more insight as to why this is the case by looking at the jQuery source code (look at the init function, in particular, the part that handles a DOM element, and the part that handles a string).

James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

I don't think these are really that different, but $("html") seems the most readable, and therefore logical option.

bevacqua
  • 47,502
  • 56
  • 171
  • 285
0

According to Addy Osmani, id and element selectors are the quickest.

http://addyosmani.com/jqprovenperformance/

See slides 21 & 25.

So I say $("html")

Agree with @AlienWebguy that you can run your own tests on jsperf.com.

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
  • 1
    I haven't profiled it, but I think in this case it will be faster to use `document.documentElement`, rather than a jQuery selector. – James Allardice Jul 10 '11 at 01:30
  • That is a comparison of selectors. If you already have direct access to the element, there's no need to run a selector. Or if you do, it will be slower because of the work it will take to process it, even if it immediately maps to the same direct reference. – user113716 Jul 10 '11 at 01:33
  • 3
    I have now profiled it, and `document.documentElement` is significantly faster: http://jsperf.com/jquery-html-selector – James Allardice Jul 10 '11 at 01:34
  • Good to know @James. +1 for your answer. – Jason Gennaro Jul 10 '11 at 01:36