gcpreston gcpreston - 6 months ago 8
Javascript Question

JavaScript - Turning an array into a list

I want to be able to turn an array, which consists of names entered by a user, into an unordered list but the list presents all the names on the first list item. How do I separate the names onto different list items?

This is what I currently have:

function createList(){
var list = document.getElementById("list");
var li = document.createElement("li");
var input = document.getElementById("q8").value;
var strComma = input.split(",");
console.log(strComma);
var i = 0;
for (i; i < strComma.length; i++){
var el = document.createTextNode(strComma[i]);
li.appendChild(el);
list.appendChild(li);
}
}

Answer

That should do a trick

function createList(){
    var list = document.getElementById("list");
    //var li = document.createElement("li");
    var input = document.getElementById("q8").value;
    var strComma = input.split(",");
    console.log(strComma);
    var i = 0;
    for (i; i < strComma.length; i++){
        var el = document.createTextNode(strComma[i]);
        var li = document.createElement("li");
        li.appendChild(el);
        list.appendChild(li);
    }
}

That way you are creating new li element and appending to the same existing ul element. In your way, where you declared li outside loop, you just referenced the same li element every time.