JavaScript: Change CSS

By Xah Lee. Date: . Last updated: .

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

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:

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: 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
CSSJavaScript
padding:1emele.style.padding="1em"
border:solid thin redele.style.border="solid thin red"
background-color:redele.style.backgroundColor="red"
font-size:largeele.style.fontSize="large"
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 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

〔➤see CSS: Tag Matching (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. JavaScript: Change CSS
  2. JavaScript: Change Element's Content
  3. JavaScript: Create HTML Element
  4. JavaScript: Remove HTML Element

  1. JavaScript: document.write
  2. JavaScript: Image Rollover
  3. JavaScript: Pop-up New Window
  4. JavaScript: Digital Clock
  5. JavaScript: Stopwatch
  6. JavaScript: Fade a Element
  7. JavaScript: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JavaScript: How to Create Tooltip
  10. JavaScript: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.