HTML DOM Document body attribute

Definition and usage

body The attribute sets or returns the document's <body> element.

Note:Set body The attribute will override all elements in the document <body>.

Tip

document.body and document.documentElement The difference is:

  • document.body returns the <body> element
  • document.documentElement returns the <html> element

See also:

Document documentElement attribute

HTML <body> Tag

HTML DOM Body Object

Example

Example 1

Get the HTML content of the document:

const myBody = document.body.innerHTML;

Try it yourself

Example 2

Change the background color of the document:

document.body.style.backgroundColor = "yellow";

Try it yourself

Example 3

Change the document's <body> (overwriting all existing content):

document.body.innerHTML = "Some new HTML content";

Try it yourself

Example 4

Create a <p> element and append it to the document body:

const para = document.createElement("p");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.body.appendChild(para);

Try it yourself

Syntax

Return the body attribute:

document.body

Set the body attribute:

document.body = newContent

Attribute value

Value Description
newContent New content of the <body> element.

Return value

Type Description
Object The body element of the document.

Browser support

document.body It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support