append()로는 문자열도 추가가 가능한데, appendChild()로는 객체만 추가할 수 있다.
li.append("문자열") → (가능)
li.appendChild("문자열") → (불가능 - typeError)
todo.js
const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input"); //todo-form 아이디를 가진 form 안에서 input을 찾는 것임!
const toDoList = document.getElementById("todo-list");
function paintToDo(newTodo) {
const li = document.createElement("li");
const span = document.createElement("span");
li.appendChild(span); //span태그를 li태그의 자식노드 리스트 마지막 자식으로 붙임. 새로운 위치로 이동하게 됨.
span.innerText = newTodo;
toDoList.appendChild(li); //html에 입력하기
}
function handleToDoSubmit(event) {
event.preventDefault();
const newTodo = toDoInput.value; //input의 value를 새로운 변수에 복사한것임.
toDoInput.value = ""; //입력후 input 비워주기
paintToDo(newTodo);
}
toDoForm.addEventListener("submit", handleToDoSubmit);
일단 1차 완성 모습>
문제점은 새로고침하면 싹 날라간다는 것!
클릭했을 때 이벤트 함수 만들어주기
target
속성은 이벤트가 발생한 대상 객체를 가리킨다.
따라서 event.target.parentElement
를 하면 이벤트가 발생한 객체를 찾아
그 객체의 부모 요소를 삭제 해주면
li > button
의 li
를 삭제주기 때문에 todo list가 삭제되는 것이다.
추가해준 코드 1.
const button = document.createElement("button");
button.innerText = "❌";
button.addEventListener("click", deleteToDo);
추가해준 코드 2.
function deleteToDo(event) {
const li = event.target.parentElement;
li.remove();
}
json.stringify 함수를 쓰고 나중에 json.parse 함수를 씀.
(STRINGIFY = 변수 등을 문자열로 바꿈,PARSE = 문자열을 JSON으로 바꿈)
localstorage 에서는 문자열만 저장할 수 있기 때문에 여기서 이렇게 쓴다.
function saveToDos() {
localStorage.setItem("todos", JSON.stringify(toDos));//객체든 배열이든 어떤 것이든 string으로 바꿔주는 기능
}
원시 자료형(primitive type)과 참조 자료형(reference data type)
<원시 자료형>
string, number, bigint, boolean, undefined, symbol, (null)
원시 자료형은 하나의 변수에는 하나의 데이터만을 담을 수 있는데, 참조 자료형은 여러 데이터를 담을 수 있다.
JSON.parse()
를 통해 string data type을 object로 바꾼거에요. 근데 이 Object는 Array 같이 바뀌었어요. 즉 index를 통해 value를 access할수 있어요예: "[a,b,c,d]" (string) => [a, b, c, d] (array);
.foreach()
라는 function 을 사용할수 있는데 이건 mdn 웹사이트 가면 나오지만 그냥 단순히 array 에 들어있는 모든 값을 iterate (순찰(?)) 할수 있는 function 입니다.(출처: 노마드코더 댓글)