Search code examples
javascripthtmlhtml-listsinnerhtml

Building UL with javascript only creates 1 li element


I'm trying to create a list using javascript. But my p tags will only take the value of the last p tag i defined.

This is my code https://jsfiddle.net/1Lt76jw2/ I tried adding in lu.appendChild(li); inbetween my p tags but that doesn't work either.

Supposed output should be

Test123

Test456

Test789

With every Test being on one p tag each


Solution

  • You should create new p and li element for each individual element:

    myUL = document.getElementById("myUL");
    var ul = document.createElement('ul');
    var li = document.createElement('li');
    var p = document.createElement('p');
    
    p.innerHTML = "Test123";
    li.appendChild(p);
    ul.appendChild(li);
    
    p = document.createElement('p');
    p.innerHTML = "Test456";
    li = document.createElement('li');
    li.appendChild(p);
    ul.appendChild(li);
    
    
    p = document.createElement('p');
    p.innerHTML = "Test789";
    li = document.createElement('li');
    li.appendChild(p);
    ul.appendChild(li);
    
    myUL.appendChild(ul);
    <div id="myUL">
    
    </div>