본문 바로가기

JS

TIL 22일 - (JS기본기) My Shopping List

JS 기본기 확인 중

문제 설명

아래 이미지처럼 상품을 추가하고 삭제할 수 있는 기능을 javascript만으로 구현해보세요.

 

우선 HTML 파일

<button> handleClick 함수를 달아주어서

input 태그에 입력된 값을 <li>에 리스팅해준다.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Shopping list example</title>
    <style>
      li {
        margin-bottom: 10px;
      }

      li button {
        font-size: 8px;
        margin-left: 20px;
        color: #666;
      }
    </style>
  </head>
  <body>
    <img src="https://developer.mozilla.org/en-US/docs/Learn/
    JavaScript/Client-side_web_APIs/
    Manipulating_documents/shopping-list.png" />
    <hr />
    <h1>My shopping list</h1>
    <div>
      <label for="item">Enter a new item:</label>
      <input type="text" name="item" id="item" />
      <button onclick="handleClick()">Add item</button>
    </div>

    <ul></ul>

    <script src="./src/box.js"></script>
  </body>
</html>

 

다음은 JS

function handleClick() {
    const myShopList = document.querySelector("ul");
    const oneList = document.createElement("li");
    const inputValue = document.querySelector("input").value;
    const input = document.querySelector("input");
    const btn = document.createElement("button");

    oneList.textContent = inputValue;
    myShopList.append(oneList);
    btn.textContent = 'Delete';
    oneList.append(btn);
    input.value = null;
  }

마지막에 input.value = null 코드를 통하여

<li>에 생성된 value값을 초기화해주었다.

 

삭제 버튼 구현

function fnDelete(event) {
  const unorderList = document.querySelector('ul');
  const deleteAll = btn.parentNode;
  const btn = event.target;
  unorderList.removeChild(deleteAll);
}

ul > li > button 구조이다.

리스트에 대상이 생성되며 동시에 삭제 버튼이 생성되고 그것이 동작이 되어야 한다.

1. ul 요소를 모두 가져오고

2. 삭제 버튼을 눌렀을 때 발생하는 이벤트 객체를 변수 btn에 담는다.

3. btn의 부모 노드 li를 deleteAll에 담고

4. 삭제 버튼 클릭시 ul의 자식 노드를 모두 삭제시켰다.