You can change the background color of an HTML element using JavaScript by setting the style.backgroundColor
property of the element.
Here’s an example of how you can change the background color of a div
element with the ID of “myDiv”:
document.getElementById("myDiv").style.backgroundColor = "red";
This will set the background color of the element with the ID “myDiv” to red. You can replace “red” with any other valid CSS color value, such as “blue”, “green”, “rgb(255, 0, 0)”, etc.
You can also use JavaScript to change the background color of multiple elements at once, for example:
document.querySelectorAll(".myClass").forEach(function(el) {
el.style.backgroundColor = "red";
});
This will change the background color of all elements with the class “myClass” to red.
You can also use the classList
API to add a class to the element, and set the background color on the CSS file of your project, like this:
document.getElementById("myDiv").classList.add("my-red-class");
And on your CSS file:
.my-red-class {
background-color: red;
}
You can also use jQuery to change the background color, like this:
$("#myDiv").css("background-color", "red");
Keep in mind that changing the background color of an element using JavaScript does not change the actual HTML or CSS of the page, it only changes the rendered visual on the browser.
Also Read:
- What Is AJAX?
- List of JavaScript Functions
- How To Copy An Array In JavaScript
- How To Get All Unique Values In A JavaScript Array
- Convert int to string in JavaScript
- How To Check If An Object Is An Array In JavaScript
- How To Randomize An Array In JavaScript
- How To Replace All Occurrences Of A Character In A String?
- How To Split A String In JavaScript?
- How To Replace Multiple Spaces With Single Space In JavaScript
- How To Replace All Character In A String In JavaScript
- How To Check If A String Contains A Substring In JavaScript
- How To Loop Through An Array In JavaScript
- How To Check If A Value Exists In An Array In JavaScript
- How To Remove Duplicates From An Array Using JavaScript
- How To Create Multiline Strings In JavaScript
- How To Remove A Specific Element From An Array In JavaScript
- How To Define A Function In JavaScript?
- How To Concatenate Two String Arrays In JavaScript
- How To Get Image Size (Height & Width) Using JavaScript
- How To Change Image Size In JavaScript
- How To Increase and Decrease Image Size Using JavaScript
- How To Trigger Or Pause A CSS Animation In JavaScript
- How To Check If A Variable Is Undefined Or Null In JavaScript
- How To Check If A Variable Exists Or Is Defined In JavaScript
- How To Change The Background Color With JavaScript
- How To Encode A URL With JavaScript
- How To Decode A URL In JavaScript