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
(?)
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
The <html> HTML element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. None. One <head> element, followed by one <body> element.
The :root selector in jQuery is used to select the root element of document. Syntax: $(":root")
The <html> element is the root element of the HTML page. The <head> element contains the document's metadata (including elements such as meta, title, style, script). The <title> element describes the title of the document.
$(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).
I don't think these are really that different, but $("html")
seems the most readable, and therefore logical option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With