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:

#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. = "#999999";

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. = "#00FF00";

Leave a Reply