todo를 삭제하는 버튼을 추가해보자. 당연히 JS에서 만들어질거다.
여기서 중요한건 버튼이 click event를 기다리고 있어햐 한다는거다. 왜냐하면 그게 누군가 뭔가를 클릭했을때 알 수 있는 유일한 방법이기 때문이다.
삭제 버튼이 클릭되면 해당 todo는 삭제가 되어야 한다. 그렇다면 클릭 되는걸 어떻게 알 수 있을까?
===> eventListener!
button.addEventListener("click",deleteToDo);
는 클릭이벤트를 감지한다. 근데 중요한건, 어디를 클릭한건지를 알 수가 없다. 어떤 li를 지워야하는가....
기억날지는 모르겠지만, 우리는 실행되는 이벤트에 대하여 기본정보를 가지고 있다!!
function deleteToDo(e){ console.log(e); }
위의 코드를 통해 어떤 정보가 있는지 확인해보자. 그 중에 path를 보면, 우리에게 어떤 element에서 클릭이 일어난 건지를 보여주고 있다. 이것은 클릭 target이 무엇인지를 체크할 수 있다는거다.
event는 property를 가지는데, e.target은 클릭된 html 요소를 알려준다.
function deleteToDo(e){ console.log(e.target); } >> <button>❌</button> >> <button>❌</button>
다 비슷하게 나오는것 처럼 보인다.
console.dir(e.target);
을 통해 더 자세하게 살펴보면 parentNode/parentElement라는게 있다. 누가 버튼의 부모냐는 거다.
어떤게 클릭되었는지 아는것만으로는 충분하지 않다. 우리는 클릭된 버튼의 parentNode 또는 parentElement를 얻고 싶다. 그걸 정확히 알아야 원하는 것을 삭제할 수 있으니까 ㅇㅇ
console.dir(e.target.parentElement.innerText);
이렇게 하면 어떤 것이 클릭되었는지 알 수 있다.
그리고 모든 HTML element에는 하나 이상의 property가 있다. 우리는 클릭된(타겟이 된) 요소의 부모 요소를 삭제해줄거다. 버튼의 부모인 리스트인 li 요소를 삭제해야하므로!!!
정리 : 버튼을 클릭할 때, 이벤트를 얻게 된다. 이벤트는 타겟을 주겠지? = 누가 클린된건지 . 타겟은 버튼이다. 버튼은 부모를 가지고 있다. 우리는 그 버튼의 부모에 접근할 수 있다. 버튼의 부모는 결국 li가 되는거다.
const toDoForm = document.getElementById("todo-form"); const toDoInput = toDoForm.querySelector("input"); const toDoList = document.getElementById("todo-list"); function deleteToDo(e){ const li = e.target.parentElement; li.remove(); } function paintToDo(newToDo){ const li = document.createElement("li"); const span = document.createElement("span"); span.innerText = newToDo; const button = document.createElement("button"); button.innerText = "❌"; button.addEventListener("click",deleteToDo); li.appendChild(span); li.appendChild(button); toDoList.appendChild(li); } function handleToDoSubmit(event){ event.preventDefault(); const newToDo = toDoInput.value; toDoInput.value = ""; paintToDo(newToDo); } toDoForm.addEventListener("submit",handleToDoSubmit);