Tree UI 과제

hyo·2022년 8월 22일
0

Tree UI

Tree UI가 재귀를 사용할 수 있는 구조임을 이해할 수 있는지 알아보는 과제이다.

위의 음료 등등 tree 구조를 가진 배열인 menu라는 상수가 있다.

const menu = [ {name: '치킨', children: [...]}, {name: '피자', ...}, {name: '족발', ...}, {name: '떡볶이', ...} ]

children속성안에는 menu와 비슷하게 name속성과 또 children속성이있다.
재귀함수를 사용하여 안으로 파고들며 접근해볼수 있다.

// 작성.js 파일
const root = document.getElementBYId('root'); // index.html의 id가 'root'인 ul태그를 read해왔다.
function createTree(menu, currentNode) {
  // 로직 작성
}

createTree(menu, root)

// index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tree UI</title>
</head>

<body>
  <ul id="root"></ul>
</body>

</html>

createTree() 함수를 실행시켰을때 위와 같은 출력이 나와야한다.

javascript없이 html로만 만들어진 result.html을 보면

<ul id="root">
      <li>
        <input type="checkbox" checked />
        <span>치킨</span>
        <ul>
          <li>
            <input type="checkbox" />
            <span>교촌치킨</span>
            <ul>
              <li>후라이드</li>
              <li>양념</li>
              <li>간장</li>
              <li>반반</li>
            </ul>
          </li>
          ...
          ...
</ul>          

이런식으로 나와있는걸 볼 수 있다.
즉, ul태그의 자식 요소로 li, input, span, ul이 있는것이다.

작성.jsroot' id를 가진 ul태그를 조회해둔걸 볼 수 있다.
-> ul태그에 추가적으로 위의 html처럼 javascript를 이용하여 DOM처럼 넣어주자.

단, 하드코딩이아닌 재귀적으로!

function createTree(menu, currentNode) {
  for(let i = 0; i < menu.length; i++){
    const liTag = document.createElement('li'); // li태그 생성
    const ulTag = document.createElement('ul'); // ul태그 생성
    const inputTag = document.createElement('input'); // input태그 생성
    inputTag.setAttribute('type', 'checkbox') // input태그에 속성주기
    const spanTag = document.createElement('span'); // span태그 생성
    spanTag.textContent = menu[i].name; // span태그의 textcontent에 menu의 i번째 객체의 name이라는 key의 값 할당 
    
    if(menu[i].children){  // menu[i]에 key가 children이 존재할때!
      liTag.append(inputTag); // li태그에 input태그 넣어주기
      liTag.append(spanTag); // li태그에 span태그 넣어주기
      liTag.append(ulTag);   // li태그에 ul태그 넣어주기
      createTreeView(menu[i].children, ulTag); // 재귀함수를 써서 인자로 menu[i].children, ulTag 넣어주기
    }
    else { // menu[i]에 key가 children이 존재하지 않을때!
      liTag.textContent = menu[i].name; // li태그의 콘텐츠에 menu[i].name만 넣어주기
    }
    currentNode.append(liTag); // currentNode에 liTag 넣어주기
  }

}

DOM과 재귀를 활용하여 작성하였다.

고민했던부분 :

-> 처음에 작성할때 li, ul, input, span 생성태그를 변수로 for문 바깥에서 선언하고 for문에서 가져와 반복적으로 사용하려고 했으나 마지막 요소만을 출력하였다.
생성메서드를 for문 내부에 작성하고 실행시키니 잘 출력하였다.

자바스크립트에서 바깥에 생성된 변수를 내부의 로직에서 가져다 쓸수있다는걸 알고있기에 당연히 바깥에서 선언된 변수도 잘 가져다 쓸 줄 알았지만 아니었다.

profile
개발 재밌다

0개의 댓글