Home  >  Article  >  Web Front-end  >  How to Dynamically Change an HTML Element's Background Color Using JavaScript?

How to Dynamically Change an HTML Element's Background Color Using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 13:37:021006browse

How to Dynamically Change an HTML Element's Background Color Using JavaScript?

CSS Properties in JavaScript: Setting Background Color

Question: How can we modify an HTML element's background color dynamically using JavaScript?

Answer: JavaScript leverages camelCase notation for accessing CSS properties, omitting dashes. Therefore, "background-color" translates to "backgroundColor."

To illustrate:

<code class="javascript">function setColor(element, color) {
    element.style.backgroundColor = color;
}

// where el is the specific element
var el = document.getElementById('elementId');
setColor(el, 'green');</code>

This code snippet demonstrates setting the background color of an element with ID "elementId" to green.

The above is the detailed content of How to Dynamically Change an HTML Element's Background Color Using 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