Bootcamp
Search…
1.11: CSS Control with DOM
When creating our apps, it's very likely that the UI will need to change in response to user actions- this will usually mean that the CSS of a given element changes.
There are several different ways to set the CSS of an element, just like there are different ways to specify CSS for a page, e.g., inline, style tag, CSS file, etc.

index.html

1
<button id="change">click me</button>
2
<h1 id="header">DOM Starter</h1>
Copied!

Style Property

The most direct way to style an element is to use the DOM element style property.

script.js

1
const button = document.querySelector('#change');
2
button.style = "color:red; font-size:20px;";
Copied!
We can set in the style string any set of CSS we want. The drawback is that it is hard to control a specific style on the element. Setting the style property of the element sets all the inline styles at once.

Class List

The best most flexible way to apply and take away CSS styles of a DOM element is to use the classList method.

script.js

1
const button = document.querySelector('#change');
2
​
3
let counter = 0;
4
​
5
button.addEventListener('click', () => {
6
const header = document.querySelector('#header');
7
​
8
if (counter % 6 === 0) {
9
header.classList.add('big');
10
} else {
11
header.classList.remove('big');
12
}
13
​
14
if (counter % 4 === 0) {
15
header.classList.add('red-text');
16
} else {
17
header.classList.remove('red-text');
18
}
19
​
20
counter += 1;
21
});
Copied!

style.css

1
.big {
2
font-size: 70px;
3
}
4
​
5
.red-text {
6
color: tomato;
7
}
Copied!
The example above independently controls the font size and text color of an element by adding and removing classes associated with that CSS.

Further Reading