How to set background color of HTML element using css properties in JavaScript
You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.
Your CSS would obviously be something like:
.highlight {
background:#ff00aa;
}
Then in JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
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');