MyInternships.in

HTML DOM

HTML DOM body Property

The body property returns the <body> element of the document. It gives JavaScript a direct handle on the main content container so you can read it, style it, or add elements to it.


Definition and Usage

document.body returns the <body> element of the current document. Because almost everything visible on a page lives inside <body>, this property is a common starting point for adding content, changing background colours, or measuring the page.

The property is read/write: you can also assign a new <body> element to document.body, which replaces the existing one, although this is rarely needed.

Syntax

document.body

Example

Click the button to change the page background colour by writing to document.body.style, and to report how many child elements the body currently has.

Style the body and count its children
Example
<!DOCTYPE html>
<html>
<body>
  <h1>document.body demo</h1>
  <button onclick="run()">Restyle the body</button>
  <p id="out"></p>

  <script>
    function run() {
      document.body.style.background = "#e0f7fa";
      document.getElementById("out").textContent =
        "The body has " + document.body.children.length + " child elements.";
    }
  </script>
</body>
</html>

More Examples

You can append new elements directly to the body. Each click adds a paragraph to the end of the page.

Append elements to document.body
Example
<!DOCTYPE html>
<html>
<body>
  <button onclick="addLine()">Add a line to the body</button>

  <script>
    function addLine() {
      const p = document.createElement("p");
      p.textContent = "A new paragraph added at " + new Date().toLocaleTimeString();
      document.body.appendChild(p);
    }
  </script>
</body>
</html>
ℹ️

Do not confuse document.body with document.documentElement. document.body is the <body> element, while document.documentElement is the root <html> element.

Key Takeaways

  • document.body returns the page's <body> element.
  • It is a common entry point for adding or styling content.
  • You can append elements to it with appendChild.
  • document.documentElement returns <html>, not <body>.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships