<!DOCTYPE html>
<html>
<head>
<title>To-Do</title>
<link rel="stylesheet" type="text/css" href="todos.css">
</head>
<body>
<ul>
<li><span>X</span> Do Programming</li>
<li><span>X</span> Do More Programming</li>
<li><span>X</span> Do more and more Programming</li>
</ul>
<script type="text/javascript" src="todos.js"></script>
</body>
</html>
css
.toggleli {
text-decoration: line-through;
color: grey;
}
Javascript
var li = document.querySelectorAll("li");
for(i=0; i < li.length; i++) {
li[i].addEventListener("click", function() {
li[i].classList.toggle("toggleli");
});
}
This is the error
todos.js:5 Uncaught TypeError: Cannot read property 'classList' of undefined
at HTMLLIElement.<anonymous>
But when i change the
li[i].classList.toggle("toggleli");
to
this.classList.toggle("toggleli");
the error goes away. Whats the problem with
li[i].classList and li.classList
inside the for loop because outside that for loop it doesn't show the error but i have to toggle all the li's so i have to put it inside the loop