Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #color #css

How to set background color of HTML element using css properties in JavaScript

I'm trying to set the background color of an HTML element using CSS properties in JavaScript, but I'm facing some issues.

I have a <div> element with the ID myElement and I want to change its background color dynamically using JavaScript.

I know I can do this using the style property, but I'm not sure how to specify the background color using CSS properties. Can someone help me with this?

save
listen
AI Answer
1 Answer
Write Your Answer
  1. Sure, I can help you out. To set the background color of an HTML element using CSS properties in JavaScript, you can use the style.backgroundColor property.
    const myElement = document.getElementById("myElement");
    myElement.style.backgroundColor = "red";

    This code will set the background color of the element with the ID myElement to red. You can replace red with any valid CSS color value like "blue", "#00ff00", or "rgb(255, 0, 0)".
    Reply Delete
    Share
loading
back
View All