Uni Uni - 6 months ago 67
HTML Question

how to add new <li> to <ul> onclick with javascript

How do I add a list element to an existing ul using a function from an onclick? I need it to add to this type of list ...

<ul id="list">
<li id="element1">One</li>
<li id="element2">Two</li>
<li id="element3">Three</li>
</ul>


... another list item with the id "element4" and text "Four" under that. I tried this function but it doesn't work...

function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
}


I don't know JQuery so Javascript only please. Thank you!!

Answer

You have not appended your li as a child to your ul element

Try this

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  ul.appendChild(li);
}

If you need to set the id , you can do so by

li.setAttribute("id", "element4");

Which turns the function into

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  li.setAttribute("id", "element4"); // added line
  ul.appendChild(li);
  alert(li.id);
}
Comments