How do I change the background color with JavaScript?

javascript

To change the background color of an element using JavaScript, you can use the style property of the element and set the backgroundColor property to the desired color value.

Here’s an example of how to change the background color of the body element to red:

document.body.style.backgroundColor = "red";

You can replace “red” with any valid CSS color value, such as “green”, “#00ff00”, “rgb(0, 255, 0)”, or any other color value that you want to use.

If you want to change the background color of a specific element other than the body, you can use the querySelector() method to select the element by its CSS selector, and then set its backgroundColor property like this:

// select an element with a specific CSS selector
let element = document.querySelector("#myElement");

// set the background color of the element
element.style.backgroundColor = "blue";

In this example, “#myElement” is a CSS selector that matches an element with the id attribute set to “myElement”. You can replace this selector with any other valid CSS selector to select the element that you want to change the background color of.