Javascript and DOM: Building Content

Using an array (a list).

let seasons = ['Spring', 'Summer', 'Autumn', 'Winter'];

Iterate through Array

Example 10.2 - Example 10.2
 
 <p>
   <button id="makelist" type="submit">Build List of Seasons   </button>
 </p>
 <div id="seasonslist2"> 
 </div>

In head element:

<script src="example2.js"> </script>

Contents of example2.js

function makeSeasonsList() {
ul_node = document.createElement("ul");
let seasons = ['Spring', 'Summer', 'Autumn', 'Winter'];
for (let i = 0 ; i < seasons.length ; i++ ) {
  let mytext = i + " " + seasons[i];
  let text_node = document.createTextNode(mytext);
  let li_node = document.createElement("li");
  li_node.appendChild(text_node);
  ul_node.appendChild(li_node);
};
let container = document.getElementById("seasonslist2");
container.appendChild(ul_node);
}
/* Wait for DOM to be loaded, then add the click listener
   to the button */
document.addEventListener('DOMContentLoaded',function(){
  document.getElementById('makelist').addEventListener('click', makeSeasonsList);
});

Using forEach array method

Example 10.3 - Example 10.3
 
 <p>
   <button id="makelist" type="submit">Build List of Seasons   </button>
 </p>
 <div id="seasonslist3"> 
 </div>

In head element:

<script src="example3.js"> </script>

Contents of example3.js

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

/* Wait for DOM to be loaded, then add the click listener
   to the button */
document.addEventListener('DOMContentLoaded',function(){
  document.getElementById('makelist').addEventListener('click', makeSeasonsList);
});