Add JavaScript Generated Text to a Div with an Array and For Loop

by Aeryith

If you’re here to learn about JavaScript, I am assuming you know basic HTML and some (minimal) programming experience. We are going to create an array in JavaScript and will use a for loop to output the generated text into a div.We’re going to store the top 10 MMO’s in an array (source):

  1. World of Warcraft
  2. Lord of the Rings Online
  3. Aion
  4. Eve Online
  5. Final Fantasy XI
  6. City of Heros
  7. Champions Online
  8. Dark Age of Camelot
  9. Warhammer Online
  10. Age of Conan

We are going to get more familiar with the following:

  • JavaScript Arrays
  • For Loop
  • Functions
  • ID’s and Divs
  • ordered lists

Ok, now on to the good stuff. Let’s create an array.

If you’re not familiar with what an array is, think of it as a mini spreadsheet (at least I do). It holds variable data in more than one ‘cell’. It can hold a list of items (one dimensional) – imagine a row of data in a spreadsheet. It can also hold more than one row of data (multi-dimensional), just like a spreadsheet. We will be working with the simple, one dimensional array.

var games = new Array(10);
games[0] = "World of Warcraft";
games[1] = "Lord of the Rings Online";
games[2] = "Aion";
games[3] = "Eve Online";
games[4] = "Final Fantasy XI";
games[5] = "City of Heros";
games[6] = "Champions Online";
games[7] = "Dark Age of Camelot";
games[8] = "Warhammer Online";
games[9] = "Age of Conan";

I want to point out three things here.

  1. You notice the array starts at 0, not 1. Computers count from 0 naturally, so keep this in mind when you’re programming.
  2. The number 10 in new Array(10) does not have to be there. You can put a number here if you want to limit how big the array gets. You might want to do this for data you get from an outside source.
  3. There is more than one way to create this array. You can create the same array like this:
var games = new Array("World of Warcraft", "Lord of the Rings Online", "Aion", "Eve Online", "Final Fantasy XI", "City of Heros", "Champions Online", "Dark Age of Camelot", "Warhammer Online", "Age of Conan")

The comma separates each item and each item is numbered automatically (remember it starts at 0).

Now we have the array, we need to create a function to start our for loop when our body content is loaded. Otherwise, you won’t see anything. Before we do that, let’s go ahead and create our body text and add the function call to our body tag.

<body onload="pageLoaded()">
<div style="width: 600px; margin: auto; padding: 15px; border: 1px solid gray; font-family: sans-serif;">
<h1&>Top 10 MMO's&<h1>
<div id="result">loading data </div>
</div>
</body>

What we’re mostly concerned with is the div with the id #result. We’re going to use this to identify the div we want our text placed in. Ok, back to our JavaScript.

We are going to create our function:

function pageLoaded(){
//create variable to hold the text generated by the for loop
var list = "<ol>";
}

We create our variable “list” to hold the text that will be generated by our for loop. We are going to output our items in an ordered list, so we add the opening ordered list tag to the variable when we declare it. We don’t want this repeated each time the for loop runs, now do we?

The For Loop

Let’s break down what this for loop does, shall we?

// set parameters for array - games.length refers to the number of items in the array
 for(i=0; i<games.length; i++){
 // adds a list item to the variable 'list' - we use += to add our strings
 list +="<li>"+games[i]+"</li>";
 }//end for

The for loop needs three parameters within it’s parenthesis. This is key to telling it how many time it’s going to repeat.

(i=0; i<games.length; i++)

i=0 – We created a variable called i, and set it’s value equal to 0 (because our array starts with 0).

i<games.length – as long as i is less than the length of the games array (how many items are stored), it will run

i++ after loop runs, add 1 to i

list +="<li>"+games[i]+"</li>";

Notice we are using += instead of just an =. If we just used an =, it would replace the old data with the new, instead of adding to it. Slick, huh?

"<li>"+games[i]+"</li>";

We cycle though the array, adding a list item each time to our variable.

We’re done with our for loop but we have a few more things to add. We need to close off our ordered list.

// created variable 'list' that will hold our ordered list
 var list = "<ol>";
 // set parameters for array - games.length refers to the number of items in the array
 for(i=0; i<games.length; i++){
 // adds a list item to the variable 'list' - we use += to add our strings
 list +="<li>"+games[i]+"</li>";
 }//end for
 // since the loop is done, add the end tag to the ordered list
 list +="</ol>";

The last thing we’re going to do is add the contents of our variable into the #result div.

// created variable 'list' that will hold our ordered list
 var list = "<ol>";
 // set parameters for array - games.length refers to the number of items in the array
 for(i=0; i<games.length; i++){
 // adds a list item to the variable 'list' - we use += to add our strings
 list +="<li>"+games[i]+"</li>";
 }//end for
 // since the loop is done, add the end tag to the ordered list
 list +="</ol>";
 // write the variable list contents (now filled with the array items) to the div #result
 document.getElementById("result").innerHTML=list;

document- this html page

getElementById(“result”) – find the element that has id=”result” tag in it. Note that this can refer to something besides a div such as an image or a link, as well as other elements.

innerHTML – while it isn’t 100% correct to use this, it works just fine in modern browsers as well as some older ones.

=list – Long story short, we’re replacing the HTML code within the #result div to what we have stored in our variable. Note that when we set the HTML code to our variable, it replaces any code or formatting you have within the div.

Here is what our finished code should look like:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Fun with JavaScript Stuffz</title>

<script type="text/javascript" language="javascript">
var games = new Array();
 games[0] = "World of Warcraft";
 games[1] = "Lord of the Rings Online";
 games[2] = "Aion";
 games[3] = "Eve Online";
 games[4] = "Final Fantasy XI";
 games[5] = "City of Heros";
 games[6] = "Champions Online";
 games[7] = "Dark Age of Camelot";
 games[8] = "Warhammer Online";
 games[9] = "Age of Conan";

function pageLoaded(){
 // created variable 'list' that will hold our ordered list
 var list = "<ol>";
 // set parameters for array - games.length refers to the number of items in the array
 for(i=0; i<games.length; i++){
 // adds a list item to the variable 'list' - we use += to add our strings
 list +="<li>"+games[i]+"</li>";
 }//end for
 // since the loop is done, add the end tag to the ordered list
 list +="</ol>";
 // write the variable list contents (now filled with the array items) to the div #result
 document.getElementById("result").innerHTML=list;
}//end pageLoaded Function

</script>
</head>

<body onload="pageLoaded()">

 <div style="width: 600px; margin: auto; padding: 15px; border: 1px solid gray; font-family: sans-serif;">
 <h1>Top 10 MMO's</h1>
 <div id="result">loading data </div>
 </div>

</body>
</html>

View Example HTML Page

I hope you enjoyed this! :)

3 Comments

  1. 20 March 12, 11:12am

    Very useful post. I’ve applied this to a JQuery Mobile app. Best!

  2. 16 April 12, 2:42am

    Awesome share!! I just love your article!

  3. Damien Smith
    20 April 12, 2:26pm

    This helped me with my JavaScript homework. You made it easy to understand, thanks!

Leave a Reply