Home » Questions » Computers [ Ask a new question ]

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

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

Asked by: Guest | Views: 471
Total answers/comments: 4
Guest [Entry]

"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');"
Guest [Entry]

"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';"
Guest [Entry]

"var element = document.getElementById('element');
element.style.background = '#FF00AA';"
Guest [Entry]

"Or, using a little jQuery:

$('#fieldID').css('background-color', '#FF6600');"