I am planning to create a simple to-do list to teach my students( I am also very new to JS)
function createlist() {
let x = document.forms["todo"]["thing"].value;
var head = document.createElement("li");
head.innerText = x;
head.style.color = "red";
head.setAttribute("id", "listid");
document.getElementById("myUL").appendChild(head);
}
I want the list elements to be deleted when I click on them! How do I dynamically create an event and link it to the list element created?
Attach a single event listener to the list element to catch events from your list elements as they "bubble up" the DOM, and then add a class to the clicked item that sets its display to none.
const list = document.querySelector('ul');
list.addEventListener('click', handleClick, false);
function handleClick(e) {
e.target.classList.add('deleted');
}
.deleted { display: none; }
li:hover { cursor: pointer; color: blue; }
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>