user3649499 user3649499 -4 years ago 82
Javascript Question

how to create new list and add list items to new list using javascript

I am trying to create a new list and add it to the DOM, and then add list items to new list along with text node to each list item.
This is what I have so far, after trying several ways to do this, but still not accomplishing goal. any help is appreciated.The first 4 lines of code is HTML snippet, the code below that is the JavaScript code. Again thank you for any help with this.

<body>
<div id="nav"></div>
<script src="js/script.js"></script>
</body>

var newList = document.createElement("ul");
var newListItem = document.createElement("li");

var stringArray = ["Home","About","Our Services","Contact Us"];

var newUL = document.getElementById("nav").appendChild(newList);

function buildList(){
for( var i = 0; i < stringArray.length; i++){
newUL.appendChild(newListItem);
}
var listItems = document.getElementsByTagName("li");

for( var i = 0; i < listItems.length; i++){
listItems[i].appendChild(stringArray[i]);
}
}

buildList();

Answer Source

You need to create a text node and append it to the <li> element.

var newList = document.createElement("ul");
var stringArray = ["Home","About","Our Services","Contact Us"];

// Create a <ul> element
var newUL = document.getElementById("nav").appendChild(newList);

function buildList(){
    for(var i = 0; i < stringArray.length; i++){
        // Create a text node
        var newTextNode = document.createTextNode(stringArray[i]); 

        // Create a list element
        var newListItem = document.createElement("li");
        
        // Append text node and list item
        newListItem.appendChild(newTextNode); 
        newUL.appendChild(newListItem); 
    }
}

buildList(); 
<body>
<div id="nav"></div>
</body>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download