nomadcoders - to do list

sang one leee·2023년 1월 31일
0

nomadcoders

목록 보기
4/10

todo.js

const toDoForm = document.querySelector("#todo-form")
const toDoInput = toDoForm.querySelector("input")
const toDoList = document.querySelector("#todo-list")

const toDos = []

function deleteToDo (event) {
    const li = event.target.parentElement
    li.remove()
}

function saveToDos () {
    localStorage.setItem("todos", JSON.stringify(toDos))
}

function paintToDo(newToDo) {
    const li = document.createElement("li")
    const span = document.createElement("span")
    const button = document.createElement("button")
    button.innerText = "X"
    button.addEventListener("click", deleteToDo)
    li.appendChild(span)
    li.appendChild(button)
    span.innerText = newToDo
    toDoList.appendChild(li)
}

function handleToDoSubmit (event) {
    event.preventDefault()
    const newToDo = toDoInput.value
    toDoInput.value = ""
    toDos.push(newToDo)
    paintToDo(newToDo)
    saveToDos()
}

toDoForm.addEventListener("submit", handleToDoSubmit)

html에서 입력받은 input.value 값을 .appendchild를 통하여 li로 출력하고 delete button도 추가한다. list에 올라온 값들을 지워지지 않게 하기 위해 localStorage.setItem으로 localstorage에 저장한다. localstorage에는 오직 string으로만 저장이 되므로 배열로 저장하기 위해 JSON.stringify()를 사용한다. JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환한다.


실행 화면

localstorage에 배열로 저장된 todos

todos "c"항목을 지우고 나서도 localstorage에 저장되어있는 "c"

profile
코린이 화이팅

0개의 댓글