DOM: Change CSS

By Xah Lee. Date: . Last updated: .

Press the following buttons to change the color.

Color Me

Here's the HTML code:

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

Here's the JavaScript code:

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

b1.addEventListener ("click", (() => ( xx.style.color="red" )) , false);
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 Attribute Name in JavaScript

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

See: CSS Attribute Name in JavaScript

βˆ‘ JS in Depth
XAH
Buy Xah JavaScript Tutorial
βˆ‘ JS in Depth
XAH

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js