I've Created element 'li' and appended two other elements(div and button) in it by creating them too.. Now when it is appended in the DOM, I want it to also dynamically be deleted when clicking Delete button, also I've grabbed all those buttons in btnid variable through which that 'li' item is to be deleted but Now I'm not getting How would I addEventListener to those buttons, If I normally add btnid.addEvent....... then it throws error coz it isn't defined yet as there's no element until an element is added dynamically.
let input = document.querySelector('#addinput') let btn = document.querySelector('#addbtn') let listcontainer = document.querySelector('#listcontainer') let btnid; btn.addEventListener('click', () => { let inpVal = input.value if (inpVal.length != 0) { let html = `<li class="margin5pxall pad5pxall"><div>${inpVal}</div><button class="btn delete">Delete</button>` listcontainer.innerHTML += html btnid = listcontainer.getElementsByTagName('button') console.log(btnid); input.classList.remove('red') } else { input.classList.add('red') } }) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="index.css"> </head> <body> <div class="mainBox flecCol bordernRad"> <div class="flexCol margin5pxall bordernRad mainHead"> <h1 class="textAlign head margin5pxall">Book List</h1> <div class="flexRow margin5pxX"> <input type="text" class="inp margin5pxall" placeholder="Search"> <button class="btn">Search</button> </div> </div> <div class="list margin5pxall bordernRad"> <ul id="listcontainer"></ul> </div> <div class="flexCol bordernRad margin5pxall lastHead"> <h1 class="textAlign head margin5pxY">Add a New Book</h1> <div class="flexRow margin5pxX"> <input type="text" class="inp margin5pxall" id="addinput" placeholder="Book Name"> <button class="btn" id="addbtn">Add</button> </div> </div> </div> </body> <script src="index.js"></script> </html>