JavaScript: Changing CSS Style

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

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.

CSS Attribute Names in JavaScript

CSS attribute name 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 attribute name and JavaScript DOM name
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'

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:

blog comments powered by Disqus