Jumpstart Lab Curriculum

DOM Basics

Output to the DOM

First, we’re going to need a place to put our output. Let’s change the body of our page:

1
2
3
4
5
6
7
<body>
  <h1>Learning Javascript</h1>
  <pre id='output'></pre>
  <script>
    // Our JavaScript will go here.
  </script>
</body>

Now, we can use some of the DOM functions to grab the pre and change its content:

1
document.getElementById('output').innerHTML = "Hello <strong>there</strong>";

That’s a pretty long way to just output some text. Let’s make a function to do it for us:

1
2
3
4
5
function output(message) {
  document.getElementById('output').innerHTML = message;
}

output("Hello friend");

Now let’s output multiple messages:

1
2
3
4
5
6
function output(message) {
  document.getElementById('output').innerHTML = message;
}

output("Hello friend");
output("Hello enemy");

This time, it will say "Hello enemy", and "Hello friend" got overwritten. We’d really like output to append to the pre each time, so we’ll use Javascript’s += operator, which will append to the string:

1
2
3
function output(message) {
  document.getElementById('output').innerHTML += message + '<br>';
}

We also add a <br> so that it breaks the line for each message.

Output based on Data

Now it’s time to join all of our powers together to output information to the dom based on some data:

1
2
3
4
5
var data = [4, 2, 9, 7];

data.forEach(function (datum) {
  output(datum);
});

Now, let’s do something crazy: a loop inside a loop!

1
2
3
4
5
6
7
8
9
10
11
var data = [4, 2, 9, 7];

data.forEach(function (datum) {
  var number = datum;
  var message = "";
  while (number > 0) {
    message += "|";
    number--;
  }
  output(message);
});

So, what’s going on here? First, we get the number from the array and set it to the number variable. Then, we create a message variable that starts off as an empty string. Next, we are going to keep looping as long as the number is greater than 0. Each time we loop, we add a | to the message, and we decrement the number with --. number-- is like saying number = number - 1. Once number hits 0, we output the message. So, each step of the loop looks like this:

Step number message
14””
23”|”
32”||”
41”|||”
50”||||”

And, we will do this for every element in our data array. The result: a bar chart, circa 1985!

||||
||
|||||||||
|||||||
Feedback

Have Feedback?

Did you find an error? Something confusing? We'd love your help:

Thanks!