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

JavascriptHtmlList

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - 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);
}

Solution 2 - Javascript

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);
}

Solution 3 - Javascript

First you have to create a li(with id and value as you required) then add it to your 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 this example that add li element to ul.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUniView Question on Stackoverflow
Solution 1 - Javascriptgaurav5430View Answer on Stackoverflow
Solution 2 - JavascriptAresView Answer on Stackoverflow
Solution 3 - JavascriptLalit Kumar MauryaView Answer on Stackoverflow