What you'r looking for is Event.stopPropagation()
createDeleteButton.addEventListener('click', function(event){
event.preventDefault(); // <= Not sure if you need this one, just for precaution
event.stopPropagation();
li.remove();
})
Edit :
list.addEventListener('click', ...
is on the ul
element so it will affect all the elements inside the ul, all the li
including the delete button i
, where ever you click inside the ul
the event will be triggered, I made some change to your code, removed the ul
event, add a checkbox for each element with an event listener, in order for your li
elements to be stroke through individually.
let input = document.querySelector('#todo');
let btn = document.querySelector('#btn');
let clear = document.querySelector('#Clear-all')
let list = document.querySelector('#list');
let el = document.getElementsByTagName('li');
// let's add the elements
function Items() {
btn.addEventListener('click', () => {
let text = input.value;
if (text === "") {
alert('You must add something in the field below');
} else {
// Create Item
let li = document.createElement("li");
list.insertBefore(li, list.childNodes[0]);
input.value = "";
// Create a text container element
const textContainer = document.createElement('b');
textContainer.innerText = text;
li.appendChild(textContainer);
// Add a delete button
const deleteButton = document.createElement("i");
deleteButton.classList.add("fa", "fa-trash");
deleteButton.innerText = "X"; // <= Remove this line if you want to remove the X
li.appendChild(deleteButton);
deleteButton.addEventListener('click', function() {
li.remove();
});
//Add a checkbox for the strike through
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
deleteButton.classList.add("fa", "fa-trash");
li.prepend(checkbox);
checkbox.addEventListener('change', function() {
if(checkbox.checked) li.classList.add("done");
else li.classList.remove("done");
});
}
})
}
Items();
// Cear all function
clear.onclick = () => {
list.innerHTML = "";
}
.done b{
text-decoration: line-through;
}
i {
color: red;
padding: 0 10px;
cursor: pointer;
}
<div class="add-element">
<input type="text" id="todo" placeholder="Type anything">
<button id="btn">Add</button>
<button id="Clear-all">Clear List</button>
</div>
<div class="element-list">
<div id="div">
<ul id="list">
</ul>
</div>
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…