Search code examples
javascriptarraysmarkup

Append an Array to an Unordered List


What I'm trying to accomplish with this code is to output the array alphabet as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <ul id="itemList"></ul>.

var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");

function write_letters(){

    for (i = 0; i < alphabet.length; i++ ) {
        document.write('<li>'  + alphabet[indexNum++] + '</li>');
    }

}

if (itemsExist){
    write_letters();
} else {
    document.write("error!");
}

Solution

  • Don't use document.write to do it. You should act like this:

    function write_letters(){
        var letters = "";
    
        for (var i = 0; i < alphabet.length; i++ ) {
            //Also I don't understand the purpose of the indexNum variable.
            //letters += "<li>"  + alphabet[indexNum++] + "</li>";
            letters += "<li>"  + alphabet[i] + "</li>";
        }
    
        document.getElementById("itemList").innerHTML = letters;
    }
    

    More proper way is to use DOM (in case you want full control of what's coming on):

    function write_letters(){
        var items = document.getElementById("itemList");
    
        for (var i = 0; i < alphabet.length; i++ ) {
            var item = document.createElement("li");
            item.innerHTML = alphabet[i];
            items.appendChild(item);
        }
    
    }