Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

like image 535
Uni Avatar asked Dec 19 '13 05:12

Uni


People also ask

What is appendChild in Javascript?

The appendChild() method allows you to add a node to the end of the list of child nodes of a specified parent node. The following illustrates the syntax of the appendChild() method: parentNode.appendChild(childNode); In this method, the childNode is the node to append to the given parent node.

Does Li have to be in UL?

The <li> HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ).

What is the difference between append and appendChild?

Element. append() can append several nodes and strings, whereas Node. appendChild() can only append one node.


2 Answers

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); } 
like image 157
gaurav5430 Avatar answered Nov 06 '22 04:11

gaurav5430


You were almost there:

You just need to append the li to ul and voila!

So just add

ul.appendChild(li); 

to the end of your function so the end function will be like this:

function function1() {   var ul = document.getElementById("list");   var li = document.createElement("li");   li.appendChild(document.createTextNode("Element 4"));   ul.appendChild(li); } 
like image 41
Ares Avatar answered Nov 06 '22 05:11

Ares