DOM: Change CSS

By Xah Lee. Date: . Last updated: .

Sample

Press the following buttons to change the color.

Color Me

Code

Here's the HTML code:

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

Here's the JavaScript code:

const xx = document.getElementById("id13959");

document.getElementById("b1").addEventListener("click", (() => ( xx.style.color="red" )) , false);

document.getElementById("b2").addEventListener("click", (() => ( xx.style.color="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.

see:

CSS Style Attribute Names in JavaScript

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. Remove Element's Attribute Value
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. DOM: Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc