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!!
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.
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> ).
Element. append() can append several nodes and strings, whereas Node. appendChild() can only append one node.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With