30 Days Of JavaScript

Day 16: DOM Manipulation

Lesson 5: Styling DOM Elements

What about styling our elements with JavaScript?

Let's expand our todo list further and highlight that some items are perhaps more important than others.

HTML to this.

1<div id="welcome-message">Welcome</div>
2<ul id="todos"></ul>

JavaScript to this.

1const isLoggedIn = true;
2const name = "Simon";
3
4const todos = [
5  { description: "Walk dog", important: true },
6  { description: "Watch TV", important: false },
7  { description: "Bake cake", important: false },
8];
9
10if (isLoggedIn) {
11  const welcomeDiv = document.getElementById("welcome-message");
12  welcomeDiv.innerText = `Welcome back ${name}`;
13}
14
15const todosList = document.getElementById("todos");
16
17todos.forEach((todoItem) => {
18  const listItem = document.createElement("li");
19  const content = document.createTextNode(todoItem.description);
20
21  if (todoItem.important) {
22    listItem.classList.add("warning");
23  }
24
25  listItem.appendChild(content);
26  todosList.appendChild(listItem);
27});

While this is probably the most complex piece of code we have looked at so far, there's nothing in here that is too challenging. The main new part is:

1if (todoItem.important) {
2  listItem.classList.add("warning");
3}

Which checks to see if the item is important: true and then adds the CSS class warning. If we look at our CSS we can see that warning makes the text orange.

classList.add() has a corresponding classList.remove().

We'll explore how that method is really handy later on for showing and hiding elements.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co