Languages
[Edit]
EN

JavaScript - change background color

0 points
Created by:
Dirask Community
6300

In this article, we would like to show you how to change background color in JavaScript.

Quick solution:

// get element by id
var myDiv = document.querySelector('#my-div');

// change background color
myDiv.style.backgroundColor = 'SpringGreen';

or:

// change document body color
document.body.style.backgroundColor = 'SpringGreen';

 

Practical examples

1. Change div background color

In this example, we get my-div element by id and change its background color.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <body>
    <div id="my-div">This is my div.</div>
    <script>
      var myDiv = document.querySelector('#my-div'); // get element by id
      myDiv.style.backgroundColor = 'SpringGreen'; // change background color
    </script>
  </body>
</html>

2. Change document body color

In this example, we change document.body background color to SpringGreen.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <body>
    <div id="my-div">This is my div.</div>
    <script>
      document.body.style.backgroundColor = 'SpringGreen'; // change body background color
    </script>
  </body>
</html>

3. Change span background color

In this example, we change the span background color, which is inside the div element.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <body>
    <div>
      My div text...
      <span id="my-span"> This is my span.</span>
      ...my div text continuation.
    </div>
    <script>
      var mySpan = document.querySelector('#my-span'); // get div element by id
      mySpan.style.backgroundColor = 'SpringGreen'; // change div background color
    </script>
  </body>
</html>
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join