1. ホーム
  2. javascript

[解決済み] how to add new <li> to <ul> onclick with javascript

2022-12-09 04:20:36

Question

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

How to solved?

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

idを設定する必要がある場合、以下のようにします。

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

これは、この関数を

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