You can see my code below. The style of the text inside the span element is supposed to change after the user checks either one of the checkboxes, but it doesn't. I tried to print the span element to the console after getting it via nextElementSibling and the result was 'undefined'. Why?
const checkBoxes = document.querySelectorAll('input[type=checkbox]');
let j = 0,
l = checkBoxes.length;
for (j; j < length; j++) {
checkBoxes[j].addEventListener("change", () => {
const spanElement = this.nextElementSibling;
console.log(spanElement);
if (this.checked) {
spanElement.style.textDecoration = "line-through";
} else {
spanElement.style.textDecoration = "";
}
});
};
ul {
list-style-type: none;
}
<h2>To-Do List</h2>
<input id="input-task" type="text">
<button id="add-task-button">Add Task</button>
<ul id="task-list">
<li>
<input type="checkbox">
<span class="task"> Send email to Bob </span>
<button class="delete-btn">Delete Task</button>
</li>
<li>
<input type="checkbox">
<span class="task"> Take vitamin D </span>
<button class="delete-btn">Delete Task</button>
</li>
<li>
<input type="checkbox">
<span class="task"> Practice coding problems </span>
<button class="delete-btn">Delete Task</button>
</li>
</ul>
It is because of arrow function which does not have it's own lexical scope, but instead takes on the one where it is defined. Replace it with function syntax and you're good to go!
window.addEventListener('DOMContentLoaded', () => {
const checkBoxes = document.querySelectorAll('input[type=checkbox]');
let j = 0,
l = checkBoxes.length;
for (j; j < l; j++) {
checkBoxes[j].addEventListener("change", function(){
const spanElement = this.nextElementSibling;
console.log('here', spanElement);
if (this.checked) {
spanElement.style.textDecoration = "line-through";
} else {
spanElement.style.textDecoration = "";
}
});
}
})
ul {
list-style-type: none;
}
<h2>To-Do List</h2>
<input id="input-task" type="text">
<button id="add-task-button">Add Task</button>
<ul id="task-list">
<li>
<input type="checkbox">
<span class="task"> Send email to Bob </span>
<button class="delete-btn">Delete Task</button>
</li>
<li>
<input type="checkbox">
<span class="task"> Take vitamin D </span>
<button class="delete-btn">Delete Task</button>
</li>
<li>
<input type="checkbox">
<span class="task"> Practice coding problems </span>
<button class="delete-btn">Delete Task</button>
</li>
</ul>