To modify your addTask()
function, follow these steps:
function addTask() {
var li = document.createElement("li");
li.setAttribute("class", "task_item"); // Updated line (1)
var inputValue = document.getElementById("input").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {} else {
document.getElementById("taskList").appendChild(li);
}
document.getElementById("input").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "taskClose";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
Make sure to add a class to your list item in step (1) to easily reference all your list items later using
document.getElementsByClassName('task_item');
.
Next, your
saveEdits()
function should be updated as shown below:
function saveEdits() {
localStorage.clear(); // Modify if needed
var elements = document.getElementsByClassName('task_item');
var taskList = []
for (var i = elements.length - 1; i >= 0; i--) {
taskList.push(elements[i].innerHTML.split("<span ")[0]);
};
var editElems = {
'edit1': taskList,
};
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
You will be referencing all your tasks as an array using
var elements = document.getElementsByClassName('task_item');
. After iterating through the list items and creating the taskList, it will be saved.
Check the web console to view the local storage:
"{"edit1":["task_3","task_2","task_1"]}"
To display your task list on refresh, update your checkEdits()
function like this:
function checkEdits() {
var userEdits = JSON.parse(localStorage.getItem('userEdits'));
if(userEdits) {
for(var elementId in userEdits.edit1) {
var li = document.createElement("li");
li.setAttribute("class", "task_item");
li.innerHTML = userEdits.edit1[elementId];
document.getElementById("taskList").appendChild(li);
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "taskClose";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
}
}
These updates should meet your requirements.
Note: There may be an issue with how you are deleting a task. Please review.