Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reference root html element with jQuery?

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

like image 458
dalgard Avatar asked Jul 10 '11 01:07

dalgard


People also ask

What is $() in jQuery?

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

How do you find the root element in html?

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.

What is jQuery root?

The :root selector in jQuery is used to select the root element of document. Syntax: $(":root")

Why is the HTML element considered the root element?

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.


2 Answers

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

like image 152
James Allardice Avatar answered Sep 29 '22 02:09

James Allardice


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

like image 31
bevacqua Avatar answered Sep 29 '22 01:09

bevacqua