Harvard Extension School, Fall 2018
CSCI E-12 Fundamentals of Web Site Development

## Javascript and DOM: Building Content

Using an array (a list).

`var seasons = ['Spring','Summer','Autumn','Winter'];`

Iterate through Array

Example 8.11 - Example 8.11 | <div id="seasonslist2"><p><button onclick="makeSeasonsList();" type="submit">Click to append list of seasons</button></p></div>function makeSeasonsList() { ul_node = document.createElement("ul"); var seasons = ['Spring','Summer','Autumn','Winter']; for (i in seasons) { var mytext = i + " " + seasons[i]; var text_node = document.createTextNode(mytext); var li_node = document.createElement("li"); li_node.appendChild(text_node); ul_node.appendChild(li_node); }; var container = document.getElementById("seasonslist2"); container.appendChild(ul_node); }

- Markup
- Script

     <div id="seasonslist2"><p><button onclick="makeSeasonsList();" type="submit">Click to append list of seasons</button></p>
    </div>

In `script` element within `head` element (`<script type="text/javascript">`):

    function makeSeasonsList() {
        ul_node = document.createElement("ul");
        var seasons = ['Spring','Summer','Autumn','Winter'];
        for (i in seasons) {
          var mytext = i + " " + seasons[i];
          var text_node = document.createTextNode(mytext);
          var li_node = document.createElement("li");
          li_node.appendChild(text_node);
          ul_node.appendChild(li_node);
        };
        var container = document.getElementById("seasonslist2");
        container.appendChild(ul_node);
    }

Using forEach array method

Example 8.12 - Example 8.12 | <div id="seasonslist3"><p><button onclick="makeSeasonsList();" type="submit">Click to append list of seasons</button></p></div>function makeSeasonsList() { ul_node = document.createElement("ul"); var seasons = ['Spring','Summer','Autumn','Winter']; seasons.forEach(function(s){ var text_node = document.createTextNode(s); var li_node = document.createElement("li"); li_node.appendChild(text_node); ul_node.appendChild(li_node); }); var container = document.getElementById("seasonslist3"); container.appendChild(ul_node); }

- Markup
- Script

     <div id="seasonslist3"><p><button onclick="makeSeasonsList();" type="submit">Click to append list of seasons</button></p>
    </div>

In `script` element within `head` element (`<script type="text/javascript">`):

    function makeSeasonsList() {
        ul_node = document.createElement("ul");
        var seasons = ['Spring','Summer','Autumn','Winter'];
        seasons.forEach(function(s){
          var text_node = document.createTextNode(s);
          var li_node = document.createElement("li");
          li_node.appendChild(text_node);
          ul_node.appendChild(li_node);
        });
        var container = document.getElementById("seasonslist3");
        container.appendChild(ul_node);
    }

Copyright © David Heitmeyer