Sometimes, we want to set background color of HTML element using CSS properties in JavaScript.
In this article, we’ll look at how to set background color of HTML element using CSS properties in JavaScript.
How to set background color of HTML element using CSS properties in JavaScript?
To set background color of HTML element using CSS properties in JavaScript, we can set the backgroundColor
style.
For instance, we write
const setColor = (element, color) => {
element.style.backgroundColor = color;
};
const el = document.getElementById("elementId");
setColor(el, "green");
to create the setColor
function.
In it, we set the lement.style.backgroundColor
property to color
to set the background color to color
.
Then we select the element we want to set the background color for with getElementById
.
And we call setColor
with it and 'green'
to set its background color to green.
Conclusion
To set background color of HTML element using CSS properties in JavaScript, we can set the backgroundColor
style.