I tried to create a function to delete individual list items by using addEventListener to the unordered list which calls a function that checks if the 'delete' button was clicked for that list item. If the 'delete' button was clicked, the function is supposed to delete the list item. But it doesn't seem to be working. Below is the code:
<!doctype html>
<html>
<head>
<meta charset='UTF-8'>
<link rel='stylesheet' href='listStyle.css'>
</head>
<body>
<h2 id='heading'>grocery list</h2>
<p>enter item into text box and press "enter" or click "submit".</p>
<p>to remove item, click "remove".</p>
<p>to reset list, click "reset".</p>
<input type = 'text' id = 'item' name = 'item'><br><br>
<button id = 'myBtn' onclick = 'myFunction()'>submit</button>
<button onclick = 'resetFcn()'>reset</button>
</form>
<script>
var str = document.getElementsByTagName('h2');
var strUpper = str[0].innerHTML.toUpperCase();
document.getElementById('heading').innerHTML = strUpper;
var res = document.createElement('ul');
res.setAttribute('id', 'myUL');
res.addEventListener('click', delBtn);
var input = document.getElementById('item');
input.addEventListener('keyup', function(event){
if(event.keyCode===13) {
document.getElementById('myBtn').click();
}
});
function myFunction() {
let x = document.getElementById('item').value;
if (x == '') {
alert ('enter input before submitting');
}
else {
document.body.appendChild(res);
var listItem = document.createElement('li');
const node = document.createTextNode(x);
var btn = document.createElement('button');
btn.innerHTML = 'remove';
btn.setAttribute('id', x);
btn.setAttribute('class', 'delete');
var att= document.createAttribute('style');
att.value = 'float: right';
btn.setAttributeNode(att);
listItem.append(x, ' ');
listItem.appendChild(btn);
res.appendChild(listItem);
item.value = '';
}
}
function resetFcn() {
while (res.firstChild) {
res.removeChild(res.firstChild);
}
}
function delBtn() {
if(event.target.classList.contains('delete')){
event.target.closest('listItem').remove();
}
}
</script>
</body>
</html>