let taskList = document.getElementById("taskList");
const newItem = new Item("some value");
taskList.append(newItem.item)
const updateTaskList = () => {
taskList.innerHTML = "";
taskItems = JSON.parse(localStorage.getItem("tasks"));
const div = document.createElement("div");
div.innerHTML = taskItems;
taskItems = div.querySelectorAll("li");
taskItems.forEach((task) => {
taskList.append(new Item("some value").item);
})
}
const updateLocal = () => {
taskList = document.getElementById("taskList");
localStorage.setItem("tasks", JSON.stringify(taskList.innerHTML));
}
class Item {
constructor(name){
const div = document.createElement("div");
div.innerHTML = name;
this.item = div;
this.item.addEventListener("click", () => this.changeStyle());
}
changeStyle(){
this.item.style.textDecoration = "line-through";
updateLocal();
}
}
document.addEventListener("DOMContentLoaded", () => {
updateTaskList();
})
The style gets updated in the DOM, but after reloading the page the style disappears instead of getting stored locally. What's the problem here.
Turns out, I was creating a new element from the Class, and not updating the style. All I had to do was pass in the styles from the local storage to the class, and update the styles for the new element.
class Item {
constructor(name, styles){
const div = document.createElement("div");
div.innerHTML = name;
if(styles) div.styles.textDecoration = styles.textDecoration;
this.item = div;
this.item.addEventListener("click", () => this.changeStyle());
}
changeStyle(){
this.item.style.textDecoration = "line-through";
updateLocal();
}
}