Reputation: 31
I have an HTML page as follows:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="style.css" />
<title>Add/Delete</title>
</head>
<body>
<h1>List of Items</h1>
<main>
<ul id="items"></ul>
<input type="text" id="newText" />
<input type="button" value="Add" onclick="addItem()" />
</main>
<script src="./app3.js"></script>
</body>
</html>
and javascript as follows:
let list = document.querySelector('#items');
let input = document.getElementById('newText');
// create Li element
let li = document.createElement('li');
// set the li element text to be the input element value plus a space
// let text = list.value + ' ';
// li.innerText = list.value
// li.innerText = list.value
li.innerText = input.value + ' ';
// create a tag
let a = document.createElement('a');
console.log(a.nodeName); // ohh ok
// set the a element text to be '[Delete]'
a.innerText = '[Delete]';
// console.log(a);
// set the a element href attribute to #
a.setAttribute('href', '#');
// append the a element to the li element
li.appendChild(a);
// console.log(li);
// appent the li element to the list element
list.appendChild(li)
// clear the input field
input.value = '';
// let x = document.getElementById('a');
// console.log(x.nodeName);
}
function deleteItem(e) {
// check if the nodeName is 'A'
// let a = doument.getElementById('a')
// if it is true remove the parent Element
}
What my problem is is that yes my addItem function works, but not my delete item function. How can I make it work? I'm confused about my understanding of removing and "checking if nodename is A". I understand that the parent element could be UL since the child elements will be list items. But if I'm checking if the nodeName is A then what does that mean? Please help.
Upvotes: 0
Views: 58
Reputation: 833
You need to add a click event listener to your <a>
element.
Under a.setAttribute('href', '#');
add the line a.addEventListener('click', deleteItem, {passive: true, once: true});
.
the passive
option makes this listener non-scroll-blocking(can't remeber the correct term for this), while once: true
removes the listener after first trigger.
It's best practice to remove unneeded event listeners.
Then do this in your delete function
function deleteItem(e) {
e.preventDefault(); /// stops default anchor behaviour('href');
let listItem = e.currentTarget.parentElement; /// selects the parent of your delete anchor
listItem.remove(); /// removes the parent from DOM
}
That's it =)
Upvotes: 2