DOM: Change CSS

By Xah Lee. Date: . Last updated: .

This page shows you how to change a element's style with JavaScript.


Press the following buttons to change the color.

Color Me


Here's the HTML code:

<span id="id13959">Color Me</span>
<button id="b1">RED</button>
<button id="b2">BLUE</button>

Here's the JavaScript code:

const xx = document.getElementById("id13959");
const button1 = document.getElementById("b1");
const button2 = document.getElementById("b2");

button1.addEventListener("click", (() => ("red") ) , false);

button2.addEventListener("click", (() => ("blue") ) , false);

This technique can be used to change the CSS value for any HTML element. All you need to do is to give the HTML tag a id attribute id=name, and define in JavaScript when should the change happen.

You can also get the element by class or tag name, if you don't have a id attribute. See: DOM: Get Elements by ID, Tag, Name, Class, CSS Selector.

CSS Style Attribute Names in JavaScript

CSS attribute names are dash separated, such as font-size. The corresponding property in JavaScript is camelCase: fontSize.


CSS Style Attribute Names in JavaScript

Basic DOM How-To

  1. DOM: Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. List/Add/Remove Class Attribute
  10. Add/Remove Event Handler
  11. DOM: Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon