Styles – alter with javascript

To alter style values within a html page via Javascript can be done two different ways, that I know of, one is via getting the object itself and then altering the style from that and the other is via the document style sheets object.

The document style sheets object is all of the styles on the web page and is index within an array manor. For example

       styleSheet = document.styleSheets[]

But since the two main browsers (Internet Explorer and also Firefox) deal with the css rules within this object with a different reference (IE = rules and FF = cssRules).

       if (styleSheet.cssRules)
              cssRule = styleSheet.cssRules[0]; // Firefox
       else if (styleSheet.rules)
              cssRule = styleSheet.rules[0];         // IE

The other method is via the id of the object, to obtain this just need to use the javascript getElementById function with the document object.

       cssRule = document.getElementById(style)

And then once the object of the style is obtained with both functions can just alter the style of the object with the same code.

       if ( == colour)
     = colour2;
     = colour;

Here is the full code



Change this style

HI there

Leave a Reply

Your email address will not be published. Required fields are marked *