Home > Article > Web Front-end > 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!