Using an array (a list).
var seasons = ['Spring','Summer','Autumn','Winter'];
Iterate through Array
<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
<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