Best way to reference root html element with jQuery?

dalgard picture dalgard · Jul 10, 2011 · Viewed 11.1k times · Source

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 (?)

Answer

James Allardice picture James Allardice · Jul 10, 2011

$(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).