JavaScript/Changing element styles

As you have seen in previous chapters, the attributes of an element can be modified by JavaScript. Two attributes, the  and , influences the visual representation of an element. They contain CSS code.

The  attribute identifies a CSS class that is created in the   element of HTML. The  attribute defines CSS rules inline (locally).

To modify them, handle them like any other attribute. They do not have special rules or exceptions.

An example
We use the above HTML file; only the JavaScript function is changed. When the button is clicked, the function assigns the CSS class 'divClassRed' to 'div_1' and it changes the inline 'style' attribute of 'div_2' to a different value.

The 'style' attribute stores the CSS properties like 'color' or 'padding' in its own properties. This correlates with the general JavaScript object rules. Therefore the following syntax is equivalent to the previous  call.

Properties of 'style'
In CSS, some properties are defined with a hyphen in their name, e.g., 'background-color' or 'font-size'. When you use them in JavaScript in the syntax of a property of style, the names change slightly. The character after the hyphen must be written in upper-case, and the hyphen disappears: 'style.backgroundColor' or 'style.fontSize'. This is called camel-case.

All other places where such names appear in CSS do not change. Especially the shown syntax with hyphens inside the HTML  element, as well as the use in the form of an inline definition, keeps unchanged.

Exercises

 * ... are available on another page (click here).