Set styles on the Body Element using JavaScript


Borislav Hadzhiev

Wed Jan 05 20222 min read


Photo by Warren Wong

Set styles on the Body Element using JavaScript #

To set styles on the body element:

  1. Use the document.body property to access the body element.
  2. Set properties on the style object of the element to update its styles.
  3. For example, = 'lime'.

Here is the HTML for the examples in this article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="background-color: salmon; width: 150px; height: 150px"> Hello world </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

// ✅ set styles on the body element = 'lime'; = 'white';

The document.body property represents the body element of the current document.

We used the style object to set CSS properties on the body.

If you need to remove a specific CSS property from the element, set it to an empty string.

Note that multi-word property names are camel-cased when using the style object.

If you don't like CSS property names being camel-cased, you can use the setProperty method instead.

index.js'background-color', 'lime');'color', 'white');

The setProperty method takes the following 3 parameters:

  1. propertyName - the name of the CSS property we want to modify. Note that property names of multiple words must be hyphenated.
  2. value - the new value for the CSS property.
  3. priority - can be set to important or empty string.

You can also use the style object to read CSS property values from the body element.

index.js = 'lime'; // ✅ read styles of the body element console.log(; // 👉️ "lime" // 👇️ "16px" console.log(window.getComputedStyle(document.body).fontSize);

The first example reads the value of the background color property on the body element.

However, this wouldn't work if the property was not set as an inline style on the element.

If you need to consider styles set in an external stylesheets, use thewindow.getComputedStyle method instead.

The getComputedStyle method returns an object that contains the values of all CSS properties of the passed in element, after applying stylesheets.

Use the search field on my Home Page to filter through my more than 1,000 articles.