JavaScript: How to 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:

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

button1.addEventListener("click", function () {"red";} , false);
button2.addEventListener("click", function () {"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: JavaScript: Get Elements by ID, Tag, Name, Class, CSS Selector.

CSS Attribute Names in JavaScript

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

Here's a table of setting styles in CSS and in JavaScript:

CSS Syntax vs JavaScript DOM Syntax
border:solid thin"solid thin red""red""large"
font-family:"DejaVu Sans",'"DejaVu Sans",sans-serif'
Google Chrome browser console completion
Google Chrome browser console JavaScript keyword completion

A easy way to check style attribute is to use browser's JavaScript console completion feature. Type then press Tab ↹, it'll show a list. 〔➤see JavaScript: How to Use Browser's JS Console

Pseudo Selectors Cannot be Scripted

CSS's pseudo selectors (➢ for example: a:visited, a:link, div.nav:before, div.nav:first-child) cannot be scripted. You can use JavaScript to script the CSS source code itself, but that is not widely supported. 〔➤see CSS Selector Syntax

thanks to NTTalex for correction.

Change HTML/XML Element Attributes

You can change a element's attribute's value in the same way. See:

Like what you read? Buy JavaScript in Depth.