Add multiple Li to Ul with javascript -


with onclick event trying add mutliple lis ul, wont add more 1 li method no matter how many appendchilds 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> 

you have make separate element each time.

try this:

var form = document.getelementbyid("form");  function newli() {     return document.createelement("li");     }  newbutton.addeventlistener("click", function(){     //create separate <ul> each time, give class, , add it.     var newul = document.createelement("ul");     newul.class = "formlist";     form.appendchild(newul);      //create new <li>'s , append them     formlist.appendchild(newli());     formlist.appendchild(newli());     formlist.appendchild(newli());      //smile. :d     } 

unlike muhammad, assume want create separate unordered list (<ul>) each time.

hence, whenever button clicked, add new <ul> , append our <li>s new <ul>.


Comments