Last updated: Mar 5, 2024
Reading time·2 min

To set styles on the body element:
document.body property to access the body element.style object of the element to update its styles.document.body.style.backgroundColor = 'lime'.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</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 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.
If you need to remove a specific CSS property from the element, set it to an empty string.
// ✅ set styles on the body element document.body.style.backgroundColor = 'lime'; document.body.style.color = 'white'; // ✅ remove styles from the body element document.body.style.backgroundColor = '';
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.
document.body.style.setProperty('background-color', 'lime'); document.body.style.setProperty('color', 'white');

The setProperty() method takes the following 3 parameters:
propertyName - the name of the CSS property we want to modify. Note that
property names of multiple words must be hyphenated.value - the new value for the CSS property.priority - can be set to important or an empty string.You can also use the style object to read CSS property values from the body
element.
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 stylesheet, use the window.getComputedStyle() method instead.
document.body.style.backgroundColor = '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.
You can learn more about the related topics by checking out the following tutorials: