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

GateKiller picture GateKiller · Aug 6, 2008 · Viewed 175k times · Source

How can I set the background color of an HTML element using css in JavaScript?

Answer

David Wengier picture David Wengier · Aug 6, 2008

In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor.

function setColor(element, color)
{
    element.style.backgroundColor = color;
}

// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');