Set styles on the Body Element using JavaScript


Borislav Hadzhiev

2 min


Photo from Unsplash

# 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.

<!DOCTYPE html> <html lang="en"> <head> <title></title> <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.
// ✅ set styles on the body element = 'lime'; = 'white'; // ✅ remove styles from the body element = '';

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

# Set styles on the body element using setProperty()

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 an empty string.

# Read CSS property values from the body element

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 stylesheet, use thewindow.getComputedStyle method instead.
index.js = 'lime'; // 👇️ "16px" console.log(window.getComputedStyle(document.body).fontSize);

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.