0

I want to add delete buttons next to each list item to delete the item when user clicked on delete button. I tried everything but i'm unable to do it. I figured I would need to create element, and then I need to have a listener, but cannot figure out how to do this right.

var inputbyuser=document.getElementById("userinput");
var button=document.getElementById("enterbutton");
var ul=document.querySelector("ul");

function lenofinput(){
    return inputbyuser.value.length;
}

function createlist(){
    var li=document.createElement("li");
    li.appendChild(document.createTextNode(inputbyuser.value));
    ul.appendChild(li);
    inputbyuser.value="";
}

button.addEventListener("click",function(){
    if(lenofinput()>0){
        createlist();
    }
})

inputbyuser.addEventListener("keypress", function(){
    if(lenofinput()>0 && event.which==13){
        createlist();
    }
})
<h1 class="DOM">TO-DO</h1>

<h1 class="todo">Today's List</h1>

<input id="userinput" type="text"  placeholder="enter text here">

<button id="enterbutton">Add To List</button>

<ul>
  <li id="firstid">Javascript </li>
  <li  random-"23">java </li>
  <li>css </li>
  <li>c</li>
  <li>Java</li>
</ul>
Mulan
  • 129,518
  • 31
  • 228
  • 259
Ayush Singh
  • 57
  • 1
  • 7
  • Does this answer your question? [How to delete an
  • from list with javascript](https://stackoverflow.com/questions/53268641/how-to-delete-an-li-from-list-with-javascript) `ul = document.querySelector('ul'); ul.addEventListener('click', function(e) { this.removeChild(e.target); })`
  • – derloopkat Apr 09 '21 at 18:04