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

How to add a list item to an existing ul using a function from onclick? I need this 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 identifier "element4" and the text "Four" below it. I tried this function, but it does not work ...

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

I do not know jQuery, so Javascript is only please. Thank!

+45
javascript list html
Dec 19 '13 at 5:16
source share
3 answers

You have not added your li as a child of the ul element

try it

 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 id, you can do it with

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

What turns this feature 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); } 
+88
Dec 19 '13 at 5:18
source share

You were almost there:

You just need to add li to ul and voila!

So just add

 ul.appendChild(li); 

to the end of your function.

+6
Dec 19 '13 at 5:18
source share

First you need to create li (with id and value as needed) and then add it to ul .

Javascript ::

 addAnother = function() { var ul = document.getElementById("list"); var li = document.createElement("li"); var children = ul.children.length + 1 li.setAttribute("id", "element"+children) li.appendChild(document.createTextNode("Element "+children)); ul.appendChild(li) } 

Check out this example adding the li element to ul .

+5
Dec 19 '13 at 5:48 on
source share



All Articles