how to add new
  • to
      onclick with javascript
  • 后端 未结 3 1430
    猫巷女王i
    猫巷女王i 2020-11-29 19:56

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

    3条回答
    •  野性不改
      2020-11-29 20:29

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

    提交回复
    热议问题