JavaScript/Changing element styles

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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

<!DOCTYPE html>
  function toggle() {
    "use strict";
    // ...
  .divClassGreen {
    background-color: green;
    padding: 2em;
    margin: 1em
  .divClassRed {
    background-color: red;
    padding: 2em;
    margin: 1em

<body id="body">
  <div id="div_1" class="divClassGreen">A DIV element</div>
  <div id="div_2" style="background-color: blue; padding: 2em; margin: 1em">Another DIV element</div>
  <button id="buttonToggle" onclick="toggle()" style="margin:1em 0em 1em 0em">Start</button>

The class attribute identifies a CSS class that is created in the style element of HTML. The style 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[edit | edit source]

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.

  function toggle() {
    "use strict";

    // locate the elements to be changed  
    const div_1 = document.getElementById("div_1");
    const div_2 = document.getElementById("div_2");

    // modify its 'class' attribute
    div_1.setAttribute("class", "divClassRed");
    // an 'inline' modification
    div_2.setAttribute("style", "background-color: silver; padding: 4em; margin: 2em");
    //or: = "background-color: silver; padding: 4em; margin: 2em";

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 div_2.setAttribute call. = "silver"; // see below: camel-case = "4em"; = "2em";

Properties of 'style'[edit | edit source]

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. = "2em"; // the font's size as property of 'style'
The next line would run into a syntax error because the hyphen
would be interpreted as a minus operation. = "2em";

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

Exercises[edit | edit source]

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

See also[edit | edit source]