JS DOM: Change CSS

By Xah Lee. Date: . Last updated: .

Press the following buttons to change the color.

Color Me

Code

<p>
<span id="x972">Color Me</span>
<button id="b1" type="button">RED</button>
<button id="b2" type="button">BLUE</button>
</p>
"use strict";
{
 const x972 = document.getElementById("x972");
 const b1 = document.getElementById("b1");
 const b2 = document.getElementById("b2");
 b1.addEventListener("click", () => {
  x972.style.color = "red";
 }, false);
 b2.addEventListener("click", () => {
  x972.style.color = "blue";
 }, false);
}

This technique can be used to change the CSS value for any HTML element. You can also get the element by class or tag name.

JavaScript DOM, Change CSS

JS DOM Common Task Examples