I am a javascript beginner and trying to make a simple list to which a user can add or remove items. Adding items to the list works but the event listeners won't work on removing an item.
txt = document.getElementById('txt_input');
submit = document.getElementById('txt_submit');
removeBtn = document.getElementsByClassName('remove');
window.onload = txt.focus();
submit.onclick = addToList;
for (var i = 0; i < removeBtn.length; i++) {
if (document.querySelector("li") !== null) {
removeBtn[i].onclick = removeFromList;
}
}
function removeFromList(e) {
event.target.parentNode.outerHTML = "";
}
function createRemoveButton(parent) {
var listBtn = document.createElement('input');
listBtn.setAttribute('type', 'submit');
listBtn.setAttribute('value', 'Remove');
listBtn.setAttribute('class', 'remove');
listBtn.style.marginLeft = '20px';
parent.appendChild(listBtn);
}
var list;
function addToList() {
if (document.querySelector("ul") === null) {
list = document.createElement('ul');
}
var listItem = document.createElement('li');
var txtNode = document.createTextNode(txt.value);
listItem.appendChild(txtNode);
createRemoveButton(listItem);
list.appendChild(listItem);
document.body.appendChild(list);
txt.value = '';
txt.focus();
}
<input type="text" id="txt_input">
<input type="submit" value="Add" id="txt_submit">
listBtn.onclick = removeFromListafter you create the remove button in yourcreateRemoveButtonfunction before adding it to the DOM.window.onload = txt.focus();is also wrong