JavaScript Document body Property

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance property

What You’ll Learn

Document.body is a standard instance property that references the <body> element holding your page content. Learn how to read it, append nodes, style backgrounds, understand MDN’s replace-body example, and handle edge cases—with five examples and try-it labs.

01

Kind

Instance property

02

Returns

HTMLBodyElement

03

Settable

Yes (careful)

04

Role

Page content

05

vs

documentElement

06

Status

Baseline widely

Introduction

Every normal HTML page has a <body> element between <head> and the closing </html>. Paragraphs, buttons, images, and app roots live inside the body. document.body is the JavaScript shortcut to that element.

It is one of the first DOM properties beginners encounter—often right after document.getElementById. You use it to append content, toggle page classes, read scroll position, and set styles such as backgroundColor (the modern replacement for deprecated document.bgColor).

💡
Content lives in the body

MDN: document.body is the element that contains the content for the document. In frameset documents it may return a frameset element instead of body.

Related Document tutorials: activeElement, ownerDocument, appendChild().

Understanding Document.body

A getter/setter instance property on Document. Reading it returns the current HTMLBodyElement (or HTMLFrameSetElement in frameset documents), or null if no such element exists.

  • ValueHTMLBodyElement | HTMLFrameSetElement | null.
  • Content container — holds visible page markup and app mount points.
  • Settable — assigning a new body replaces the old one and removes its children (MDN).
  • Common readsdocument.body.children, scrollTop, classList.
  • Not the rootdocument.documentElement is the <html> element above body.

📝 Syntax

JavaScript
document.body

Get

JavaScript
console.log(document.body.tagName); // "BODY"
console.log(document.body.id);

Set (MDN — advanced)

JavaScript
const newBody = document.createElement("body");
newBody.id = "newBodyElement";
document.body = newBody; // replaces old body — removes its children

⚡ Quick Reference

GoalCode / note
Get body elementdocument.body
Append a nodedocument.body.appendChild(el)
Body background (modern)document.body.style.backgroundColor
Toggle page classdocument.body.classList.add("dark")
Scroll positiondocument.body.scrollTop (with documentElement in some browsers)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.body.

Type
HTMLBodyElement

Usually

Role
page content

Visible DOM

Settable
yes

Replaces body

Status
baseline

Standard API

📋 body vs documentElement

document.bodydocument.documentElement
Element<body><html>
ContainsPage contentEntire document root
Can be null?Yes (no body yet)Essentially always present
Theme onBody background, layoutRoot font-size, lang, full-page CSS vars

Examples Gallery

Examples follow MDN Document: body. Use View Output or Try It Yourself for each case.

📚 Getting Started

Read the body element and use it for everyday DOM tasks.

Example 1 — Read document.body.id (MDN)

Access a property on the body element directly.

JavaScript
// HTML: <body id="oldBodyElement"></body>
console.log(document.body.id); // "oldBodyElement"
console.log(document.body.tagName); // "BODY"
Try It Yourself

How It Works

document.body is a live reference—mutations on it immediately affect the page.

Example 2 — Append Content with appendChild

Add a new paragraph to the page content container.

JavaScript
const p = document.createElement("p");
p.textContent = "Hello from document.body!";
document.body.appendChild(p);
Try It Yourself

How It Works

See also Node.appendChild() for full append semantics and return values.

📈 Styling, Replace & Safety

Body-level styles, MDN replace pattern, and null guards.

Example 3 — Style Background via body.style

Modern way to set page background color on the body element.

JavaScript
document.body.style.backgroundColor = "#f0f9ff";
document.body.style.color = "#0c4a6e";
console.log(document.body.style.backgroundColor);
Try It Yourself

How It Works

Prefer CSS rules in stylesheets for static themes; use body.style for runtime toggles (dark mode, etc.).

Example 4 — Replace Body (MDN Advanced)

Assign a new body element—MDN warns this removes existing children.

JavaScript
const newBodyElement = document.createElement("body");
newBodyElement.id = "newBodyElement";
document.body = newBodyElement;
console.log(document.body.id); // "newBodyElement"
Try It Yourself

How It Works

Rare in production apps. Use only when you understand MDN’s warning about wiping body contents.

Example 5 — Guard When body May Be Missing

Defensive check before scripts that run during early parsing.

JavaScript
if (document.body) {
  document.body.classList.add("js-ready");
  console.log("body ready:", document.body.tagName);
} else {
  console.log("body not available yet");
}
Try It Yourself

How It Works

Scripts in <head> without defer may run before <body> exists. Use DOMContentLoaded or place scripts at end of body when possible.

🚀 Common Use Cases

  • Dynamic UI — append modals, toasts, and tooltips to document.body.
  • Theme toggles — add dark class on body for site-wide dark mode.
  • Scroll locking — set overflow: hidden on body when a modal opens.
  • Analytics / error overlays — inject debug panels at the document level.
  • SPA mount — find or create app root inside body (prefer dedicated #app id).
  • Legacy migration — replace document.bgColor with document.body.style.backgroundColor.

🧠 How document.body Fits the DOM

1

Browser parses HTML

Builds htmlhead + body tree.

Parse
2

document.body available

Property references the live HTMLBodyElement.

Reference
3

Scripts mutate content

Append nodes, toggle classes, or set inline styles.

DOM
4

Page updates in place

Changes through document.body render immediately in the browser.

📝 Notes

  • MDN: Baseline Widely available (since May 2018) — no Deprecated / Experimental / Non-standard banner.
  • Setting a new body removes all children of the previous body (MDN).
  • In frameset documents, returns the outermost frameset element instead of body.
  • May be null if no body element exists yet.
  • Pair with document.documentElement for root-level styling vs content-level styling.
  • Related: bgColor, ownerDocument, activeElement.

Universal Browser Support

Document.body is marked Baseline Widely available on MDN (since May 2018). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

Document.body

Standard reference to the HTML body element — essential for page content, styling, and DOM manipulation.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Supported in legacy IE
Full support
Document.body Excellent

Bottom line: Use document.body to access and update page content. Prefer dedicated mount nodes and CSS for structure — avoid replacing the entire body unless you fully understand MDN's warning.

Conclusion

Document.body is the standard gateway to your page’s visible content. Use it to append elements, apply body-level classes, and coordinate layout—while remembering that replacing the body wipes its children.

Continue with characterSet, ownerDocument, bgColor, appendChild(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use document.body for page-wide classes and scroll lock
  • Append portals (modals, toasts) to body when needed
  • Check document.body before early head scripts run
  • Prefer CSS on body for static page backgrounds
  • Use a dedicated #app mount for SPA frameworks

❌ Don’t

  • Assign document.body = newBody casually in apps
  • Assume body exists in scripts in <head> without waiting
  • Confuse body with documentElement
  • Dump unstructured HTML into body without sanitizing user input
  • Rely on deprecated document.bgColor instead of CSS

Key Takeaways

Knowledge Unlocked

Five things to remember about document.body

Standard body reference — your page content container.

5
Core concepts
02

Status

baseline

Standard
📦03

Role

page content

DOM
⚠️04

Set body

wipes children

MDN
🛠05

Style

body.style

CSSOM

❓ Frequently Asked Questions

The HTMLBodyElement (or HTMLFrameSetElement in frameset documents) that contains the visible page content — or null if no such element exists yet.
No. MDN marks Document.body as Baseline Widely available (since May 2018). It is a standard, widely used DOM property.
Yes. The property is settable. Assigning a new body element replaces the current one and effectively removes all existing children of the old body (MDN).
document.documentElement is the root html element. document.body is the body (or frameset) inside it that holds the page content you usually manipulate.
If the document has no body element yet (for example while HTML is still parsing) or in unusual document types without a body. Always check before use in edge cases.
Yes, when you need the page content container — for appending nodes, reading scroll position, or setting body-level styles. Prefer semantic selectors when a specific element is clearer.
Did you know?

Many accessibility guidelines recommend moving focus to document.body or a main landmark after SPA route changes so screen-reader users hear the new page content. The body is often the fallback active element when nothing else is focused.

Next: characterSet

Learn how to read the document encoding label (such as UTF-8).

characterSet →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful