Home > Web Front-end > CSS Tutorial > 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
Release: 2024-11-04 13:37:02
Original
1031 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template