Styles in JavaScript

The style of a web page is usually set with CSS (Cascade Style Sheet). In a CSS document you might have something like this:

<style>
#div_1 {
color: #000000;
background-color: #FFFFFF;
}
#div_2 { border-style: solid; border-width: 1px; border-color: #000000; } </style>

This code gives you style attributes for two ids, div_1 and div_2, which means we have one div element with “id=div_1” and another div element with “id=div_2”.

JavaScript can access these divs using document.getElementById() method.

var d1 = document.getElementById("div_1");
var d2 = document.getElementById("div_2");

In order to modify the style of an element via JavaScript we have to use the style property.

d1.style.color = "#999999";

Note:
The CSS property background-color won’t work in the example above because JavaScript doesn’t allow hyphens to be part of names. However, if you use backgroundColor instead of background-color then everything will work perfectly. The rule is: eliminate the hyphen and capitalize the word that follows it.

d1.style.backgroundColor = "#00FF00";

Leave a Reply