CKTIS / JavaScript
`document.body` vs. `document.documentElement`
Use `document.body` to access the page’s content element and `document.documentElement` to access the document’s root element. Either property can return `null`.
Version: Current web platform; runtime support varies
Syntax
document.body
document.documentElement
document.body = newBodyThe distinction in Document.body/documentElement is between the page’s content container and the document’s root. document.documentElement returns the root element, or null if there is none. On a normal HTML page the root is <html>; in an XML document the root can have a different name. The property is read-only, but you can modify the returned element, for example by setting its lang attribute.
document.body returns the first direct child of the root <html> that is a <body> or a legacy <frameset>. All three element names refer to elements in the HTML namespace. If there is no matching child, or the root is not an HTML <html> element, it returns null. On a normal HTML page, add page content to <body>, not directly to <html>.
Assigning a new element to document.body replaces the existing body and its subtree instead of adding content to it. If there is no body, the setter appends the supplied element to the root. Assigning null or an element other than an HTML <body> or <frameset>, or trying to insert when there is no root, throws a HierarchyRequestError DOMException.
The HTML Standard defines document.body, and the DOM Standard defines document.documentElement. Neither property is part of ECMAScript 2024. A runtime without a page DOM may not expose the global document. A script running during parsing can see the root before the parser creates <body>. Check for null before using either result; on a normal page, you can wait for DOMContentLoaded if parsing is still in progress.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Document body and root</title>
</head>
<body>
<script>
{
const doc = document.implementation.createHTMLDocument();
const root = doc.documentElement;
const body = doc.body;
console.log(`${root.localName} > ${body.localName}`);
console.log(body.parentElement === root);
body.remove();
console.log(doc.body === null);
console.log(doc.documentElement === root);
}
</script>
</body>
</html>Result
html > body true true true
Save the example as an HTML file, open it in a browser, and check the developer console. The script creates a separate HTML document, logs the element names, and checks the parent-child relationship. After `<body>` is removed, `doc.body` returns `null` and the root is still the same object. The open page is unchanged.
Related lessons
- JavaScript · Lesson 32 · Intermediate · Version: 3