JS: 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 () {xx.style.color="red";} , false);
button2.addEventListener("click", function () {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 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 redele.style.border="solid thin red"
font-family:"DejaVu Sans",sans-serifele.style.fontFamily='"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 document.body.style. then press Tab, it'll show a list. [see JS: How to Use Browser 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]

[see CSS: Selector Tutorial]

thanks to NTTalex for correction.

Change HTML/XML Element Attributes

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

Simple DOM Examples

  1. JS: Change CSS
  2. DOM: Change Element's Content
  3. DOM: Create HTML Element
  4. DOM: Remove HTML Element

  1. JS: document.write
  2. JS: Image Rollover
  3. JS: Pop-up New Window
  4. JS: Digital Clock
  5. JS: Stopwatch
  6. JS: Fade a Element
  7. JS: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JS: How to Create Tooltip
  10. JS: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon