JavaScript/Changing element styles
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>
<html>
<head>
<script>
function toggle() {
"use strict";
// ...
}
</script>
<style>
.divClassGreen {
background-color: green;
padding: 2em;
margin: 1em
}
.divClassRed {
background-color: red;
padding: 2em;
margin: 1em
}
</style>
</head>
<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>
</body>
</html>
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
editWe 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: div_2.style = "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.
div_2.style.backgroundColor = "silver"; // see below: camel-case
div_2.style.padding = "4em";
div_2.style.margin = "2em";
Properties of 'style'
editIn 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.
div_1.style.fontSize = "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.
div_1.style.font-size = "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.