JavaScript: How to Change CSS

, , …,

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.

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'

Pseudo Selectors Cannot be Scripted

CSS's pseudo selectors (⁖ 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. 〔➤ 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? Please tell friends, share link, or Buy JavaScript in Depth. Thanks.
blog comments powered by Disqus