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

## Javascript and DOM: Building Content

Example 8.10 - Example 8.10 | <div id="seasonslist1"><p><button onclick="makeSeasonsList(); return false;" type="submit">Click to append list of seasons</button></p></div>function makeSeasonsList() { var ul_node = document.createElement("ul"); // Autumn var li_node1 = document.createElement("li"); var li_text1 = document.createTextNode("Autumn"); li_node1.appendChild(li_text1); // Winter var li_node2 = document.createElement("li"); var li_text2 = document.createTextNode("Winter"); li_node2.appendChild(li_text2); // Spring var li_node3 = document.createElement("li"); var li_text3 = document.createTextNode("Spring"); li_node3.appendChild(li_text3); // Summer var li_node4 = document.createElement("li"); var li_text4 = document.createTextNode("Summer"); li_node4.appendChild(li_text4); // Append the list items to the ul ul_node.appendChild(li_node1); ul_node.appendChild(li_node2); ul_node.appendChild(li_node3); ul_node.appendChild(li_node4); // Place on page var container = document.getElementById("seasonslist1"); container.appendChild(ul_node); }

- Markup
- Script

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

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

    function makeSeasonsList() {
        var ul_node = document.createElement("ul");

        // Autumn
        var li_node1 = document.createElement("li");
        var li_text1 = document.createTextNode("Autumn");
        li_node1.appendChild(li_text1);

        // Winter
        var li_node2 = document.createElement("li");
        var li_text2 = document.createTextNode("Winter");
        li_node2.appendChild(li_text2);

        // Spring
        var li_node3 = document.createElement("li");
        var li_text3 = document.createTextNode("Spring");
        li_node3.appendChild(li_text3);

        // Summer
        var li_node4 = document.createElement("li");
        var li_text4 = document.createTextNode("Summer");
        li_node4.appendChild(li_text4);

        // Append the list items to the ul
        ul_node.appendChild(li_node1);
        ul_node.appendChild(li_node2);
        ul_node.appendChild(li_node3);
        ul_node.appendChild(li_node4);

        // Place on page
        var container = document.getElementById("seasonslist1");
        container.appendChild(ul_node);
    }

Copyright © David Heitmeyer