Bootcamp
Search…
1.2.1: Creating Elements

Introduction

The document object allows us to create HTML elements in JS and display them programmatically.

Examples and Tips

The following example demonstrates how to create an add a DOM element to a page. We use const to declare coolParagraph because we do not expect to reassign coolParagraph. See 1.2: ES6 to review const.
1
const coolParagraph = document.createElement('p');
2
coolParagraph.innerText = 'hey, cool!';
Copied!
After we've created coolParagraph we add it to the page with appendChild on a node we know exists in the DOM, the document body.
1
document.body.appendChild(coolParagraph);
Copied!
When working with DOM elements in JS, remember the following 3 points.
  1. 1.
    Elements are not visible unless they are appended to any element already in the DOM on the page.
  2. 2.
    Elements are empty unless we append something to them or set their contents.
  3. 3.
    We can debug by inspecting the HTML elements we added in the DevTools Elements tab.

Exercises

Setup

  1. 3.
    Copy the following CSS into the style.css file.
1
.word {
2
background-color: pink;
3
margin: 0 4px;
4
padding: 10px;
5
}
6
​
7
.row {
8
background-color: yellow;
9
margin: 15px;
10
padding: 20px;
11
}
12
​
13
.container {
14
background-color: grey;
15
margin: 15px;
16
padding: 20px;
17
}
Copied!

Basic Element Creation

Create this set of HTML elements on the page using JS. The set of elements would look like the following in HTML.
1
<div class="container">
2
<div class="row">
3
<span class="word">hello</span>
4
<span class="word">papaya</span>
5
</div>
6
<div class="row">
7
<span class="word">banana</span>
8
<span class="word">world</span>
9
</div>
10
</div>
Copied!
The elements should look something like this on the page.

Element Creation in a Loop

Write a loop to create 6 grey boxes like the one above with corresponding internal boxes. The top-left-most pink box in each grey box should display the index of the grey box, e.g. 1 through 6.

Element Contents From an Array

Use this array to populate words in the pink boxes, 1 word per box. For this particular exercise, modify our grey boxes to only have 1 yellow box with 6 pink boxes in it.
1
const words = ['banana', 'pasta', 'alligator', 'purple', 'accurate', 'fickle'];
Copied!

Element Contents From an Array of Arrays

  1. 1.
    For each grey box, use the following array of arrays to create a series of yellow boxes with pink boxes inside
  2. 2.
    The food (1st nested array) should be in 1 yellow box, and the objects (2nd nested array) in another yellow box
  3. 3.
    Each of the words should appear in its own pink box within its respective yellow box
1
const words = [
2
['orange', 'tomato'],
3
['fire engine', 'basketball'],
4
];
Copied!

Refactor

Create a function that can be used to create yellow boxes from the exercises above. This function accepts the contents of the internal pink boxes as a parameter of type array, for example ['orange', 'tomato']