How To Set Styles On The Body Element Using JavaScript

Set styles on the Body Element using JavaScript

JavaScript offers some simple ways to set styles or something on the body to another style. Today we will show you how to set styles on the body element using JavaScript. This article will show you two methods like using the setProperty method, using the getElementByTagName() method. Start reading the detailed article.

Set styles on the body element using JavaScript

Using the setProperty() method

The setProperty() function is set to modify or new an existing CSS property in a declaration block.

Syntax:

object.setProperty(property, value, priority)

Parameters:

  • property: name of the property to set.
  • value: the new value.
  • priority: is a string.

Return value: The return value is new or modifies an existing CSS property in a CSS.

Code example:

In this example, we create the body variable to get the style of all elements on the body tag. Then we call the setProperty method with the value displayed, and the property is flow-root to change the style of the body tag from inline-flex to flow-root. Like the example below:

<!DOCTYPE html>
<html>
  <body id="body" style="display:inline-flex;">
    
    <h1>Welcome to LearnShareIT</h1>
    <h2>Set styles on the Body Element</h2>
    <p>Using the setProperty() method</p>
    
    <script>
      const body = document.body.style;

      // Using the setProperty method
      body.setProperty("display", "flow-root");
    </script>
  </body>
</html>

Output:

Using the document.body.style

The simplest and easiest to use is to call the document.body.style and then set the style for the body in any style you like. See the example below:

Example

<!DOCTYPE html>
<html>
<body style="display:inline-flex;">

  <h1>Welcome to LearnShareIT</h1>
  <h2>Set styles on the Body Element</h2>
  <p>Using the document.body.style</p>

<script>
	// Using the document.body.style
	document.body.style.display = "flow-root";
</script>

</body>
</html> 

Output:

Using the getElementByTagName() method

The simplest and easiest is using the getElementByTagName(). This method is very common to get the JavaScript HTML DOM elements.

Example:

<!DOCTYPE html>
<html>
<body style="display:inline-flex;">

  <h1>Welcome to LearnShareIT</h1>
  <h2>Set styles on the Body Element</h2>
  <p>Using the getElementByTagName() method</p>

<script>
	// Using the getElementsByTagName method
	document.getElementsByTagName("body")[0].style.display = "flow-root";
</script>
</body>
</html>

Output:

Summary

Hopefully, through the ways outlined above, you can easily find for yourself the best way to set styles on the body element. But we prefer using the document.body.style method to do it, how about your opinion? Leave your comment here to let us know.

Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *