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 |
|
Now, we can use some of the DOM functions to grab the pre
and change its content:
1
|
|
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 |
|
Now let’s output multiple messages:
1 2 3 4 5 6 |
|
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 |
|
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 |
|
Now, let’s do something crazy: a loop inside a loop!
1 2 3 4 5 6 7 8 9 10 11 |
|
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 |
---|---|---|
1 | 4 | ”” |
2 | 3 | ”|” |
3 | 2 | ”||” |
4 | 1 | ”|||” |
5 | 0 | ”||||” |
And, we will do this for every element in our data array. The result: a bar chart, circa 1985!
|||| || ||||||||| |||||||