Set styles on the Body Element using JavaScript

avatar

Borislav Hadzhiev

Wed Jan 05 20222 min read

banner

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, document.body.style.backgroundColor = 'lime'.

Here is the HTML for the examples in this article.

index.html
<!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.

index.js
// โœ… set styles on the body element document.body.style.backgroundColor = 'lime'; document.body.style.color = '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.

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
document.body.style.setProperty('background-color', 'lime'); document.body.style.setProperty('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
document.body.style.backgroundColor = 'lime'; // โœ… read styles of the body element console.log(document.body.style.backgroundColor); // ๐Ÿ‘‰๏ธ "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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee