I have an existing list of li
elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li
, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for
loop. Is there another method you would recommend to address this issue? I have already attempted using e.target.matches
and e.target.tagName === 'SPAN'
.
/* eslint-disable require-jsdoc */
/* eslint-disable no-invalid-this */
/* eslint-disable no-var */
// Select all necessary elements from the DOM
var deleteTodo = document.querySelectorAll('span');
var strikeThrough = document.querySelectorAll('li');
var input = document.querySelector('input');
var ul = document.querySelector('ul');
// Delete completed todos
for (var i = 0; i < deleteTodo.length; i++) {
deleteTodo[i].addEventListener('click', function(e) {
if (e.target.tagName === 'SPAN') {
console.log('Span clicked');
}
});
}
// Apply strikethrough effect to completed todos
for (var i = 0; i < strikeThrough.length; i++) {
strikeThrough[i].addEventListener('click', function(e) {
if (e.target.matches('li')) {
this.classList.toggle('done');
}
});
}
// Add a new todo task
input.addEventListener('keypress', function(e) {
if (event.keyCode === 13) {
var newTodo = input.value;
var newLi = document.createElement('li');
newLi.innerHTML = '<span>X</span> ' + newTodo;
this.value = '';
ul.appendChild(newLi);
}
});
<!DOCTYPE html>
<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>2Do</title>
</head>
<body>
<div class="container"></div>
<h1>2-Do List</h1>
<input type="text" placeholder="Add New Todo" />
<div>
<ul>
<li><span>X</span> one</li>
<li><span>X</span> Two</li>
<li><span>X</span> Task Three</li>
</ul>
</div>
<script src="script.js"></script>
</body>
</html>