Home >Web Front-end >CSS Tutorial >How to Change HTML Element Background Color with CSS via JavaScript?

How to Change HTML Element Background Color with CSS via JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 04:49:021052browse

How to Change HTML Element Background Color with CSS via JavaScript?

Changing HTML Element Background Color with CSS via JavaScript

The challenge of customizing an element's background color in HTML using CSS through JavaScript arises frequently.

To address this, CSS properties are transformed into JavaScript counterparts by employing camelCase notation and omitting dashes. Consequently, "background-color" becomes "backgroundColor".

Here's a comprehensive code demonstration:

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

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

By employing this methodology, you can effectively alter the background color of HTML elements dynamically using JavaScript.

The above is the detailed content of How to Change HTML Element Background Color with CSS via JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn