How to change the background with JavaScript

January 31, 2022

How to change the background with JavaScript

In this article we will see how to change the background with JavaScript, in a simple way so that the elements have the necessary background color

change the background with JavaScript cover

Hey you programmer, ok? Let’s learn something new! 😀

Do we know that with CSS we can change the element’s background color with background-color and with JS?

It’s very easy too, and first we need to select the element

Then we need to enter the style property and modify the backgroundColor property value inside style, to the color value we want

And then the color will be replaced in the HTML, replicating to the web page

Let’s take a practical example:

<div id="container"></div>

This is our HTML, notice that we have a #container element that we will later change the background

| Do you want to specialize in Web Development? Take a look at our course catalog.

And see this example in  CSS as well:

#container {
 width: 500px;
 height: 200px;
 border: 1px solid red;

We just delimit a height and width, and we also add a border

See the return  in the browser:

And now JavaScript will perform the magic, just check it out:

let container = document.getElementById('container'); = '#000';

As said before, we select the element with getElementById

And finally we change the backgroundColor to #000, which is black

Take a look how it looks like in the browser: EE

And that way our  goal was reached, we were able to change the background with JavaScript in an easy and fast way


In this article we learned how to change the background of an element in HTML with JavaScript

We use a method of selection by id, getElementById, and then we change the backgroundColor property that is in the style property

So changing the background color of the target div

Want to learn more about CSS? Click here!

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x