Search code examples
javascripthtmllistinputhtml-lists

html input create li element how to set an id for the element


I'm new with HTML & JS and I face the following problem:

I have an input in html that creates a new li Element (in combination with JS); is it possible to give every newly-created li element its own id? For example to delete an specific element?

For Example:

<li id="one"> .. </li>
<li id="two"> .. </li>

So far it creates only <li> ... </li>

I think it can be done with a for loop, but I have no idea how to use it in my case.

See my JS code below:

function NewEntry() {
    var Inputfield = document.getElementById("Inputfield");
    var AddButton = document.getElementById("AddButton");
    var ul = document.querySelector("ul");
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(Input.value));
    ul.appendChild(li);
    Input.value = "";

I tried to insert a for loop into my code, but after that it doesn't add any elements.

function NewEntry() {
    var Inputfield = document.getElementById("Inputfield");
    var AddButton = document.getElementById("AddButton");
    var ul = document.querySelector("ul");
    var li = document.createElement("li");
    for (var i = 0; i < li.length; i++)
      li[i].id = 'abc-' + i;
      li.appendChild(document.createTextNode(Input.value));
      ul.appendChild(li);
    Input.value = "";

Solution

  • Your for loop needs curly braces to work properly:

    function NewEntry() {
      var Inputfield = document.getElementById("Inputfield");
      var AddButton = document.getElementById("AddButton");
      var ul = document.querySelector("ul");
      var li = document.createElement("li");
      for (var i = 0; i < li.length; i++) {
        abcElements[i].id = 'abc-' + i;
        li.appendChild(document.createTextNode(Inputfield.value));
        ul.appendChild(li);
      }
      Inputfield.value = "";
    }
    

    Otherwise only the immediate line after the for statement will run as part of the loop.

    There also appeared to be a typo - you had Input instead of Inputfield? But I notice there are some other variables used here which are not defined, so I assume some extra code was omitted?