Frans B Frans B - 3 months ago 14
Javascript Question

Add multiple Li to Ul with javascript

With the onclick event I am trying to add mutliple LIs to UL, It wont add more than one Li with this method no matter how many appendChilds I do.

var form = document.getElementById("form");
var newUl = document.createElement('ul');
var newLi = document.createElement('li');

newButton.addEventListener("click", function(){
form.appendChild(newUl);
newUl.id = "formList";
var formList = document.getElementById("formList");
formList.appendChild(newLi);
formList.appendChild(newLi);
formList.appendChild(newLi);
}

//// html
<div id="form">

</div>

Answer

You have to make a separate element each time.

Try this:

var form = document.getElementById("form");

function newLi() {
    return document.createElement("li");
    }

newButton.addEventListener("click", function(){
    //Create a separate <ul> each time, give it a class, and add it.
    var newUl = document.createElement("ul");
    newUl.class = "formList";
    form.appendChild(newUl);

    //create new <li>'s and append them
    formList.appendChild(newLi());
    formList.appendChild(newLi());
    formList.appendChild(newLi());

    //smile. :D
    }

Unlike Muhammad, I assume that you want to create a separate unordered list (<ul>) each time.

Hence, whenever the button is clicked, we add a new <ul> and then append our <li>s into the new <ul>.