how to add new <li> to <ul> onclick with javascript
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);
}
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);
}