24

I can select the body and html parts of the document using

$('body')

and

$('html')

respectively, but how do I select the document root?

tomsv
  • 7,207
  • 6
  • 55
  • 88
  • 1
    Why do you want to? You don't *have* to use jQuery for everything - it's perfectly fine to use javascript too. – Ariel Jul 26 '12 at 09:34
  • Funny enough `$(document).html()` returns `null` here (using _jQuery 1.71_), while `$(document).text()` returns the expected result. – zrajm Mar 28 '13 at 18:00

3 Answers3

36

Not sure what you mean, but to select the document you do

$(document);

To get the contents of the document I'm guessing you need the documentElement, which is just the same as the <html> tag in most enviroments.

$(document.documentElement);
adeneo
  • 312,895
  • 29
  • 395
  • 388
4

The root of the DOM is always the html element.
You can get it either with $('html') or $(':root').

The following assertions should always be true:

$('html')[0] === $(':root')[0]
$(':root')[0] === document.documentElement
GetFree
  • 40,278
  • 18
  • 77
  • 104
2

The Document interface inherits from Node, and represents the whole document, such as an HTML page. Although the Document node is conceptually the root of a document, it isn't physically the root - the root node is the first Element node in the Document, and is represented by its documentElement property.

You can select documentElement with following code:

var root = document.documentElement;

OR

$(document.documentElement);
Alok Jain
  • 3,379
  • 3
  • 23
  • 42