children이 있을 때와 없을 때를 비교해서 code를 작성해주면 된다.
fixme.js
const root = document.getElementById('root');
function createTreeView(menu, currentNode) {
for (let i = 0; i < menu.length; i++) {
const li = document.createElement('li');
// 자식이 있을 때
if (menu[i].children) {
const input = document.createElement('input');
input.type = 'checkbox';
//카테고리 이름을 span태그로 감싸야 합니다
const span = document.createElement('span');
span.textContent = menu[i].name;
//자식 노드가 있는 데이터일경우 ,
//자식 노드를 렌더링할 새로운 ul
const ul = document.createElement('ul');
// 만들어 줬던 것들을 li에 넣어준뒤
li.append(input, span, ul);
// root에 넣어준다
currentNode.append(li);
createTreeView(menu[i].children, ul);
// 재귀함수를 이용해서 자식노드 생성
// 두번째로 돌아갈때 각 요소의 childern
// 현재 노드는 ul
} else {
// 자식노드가 없을때는 이름만 표시한다
li.textContent = menu[i].name;
currentNode.append(li);
}
}
}
createTreeView(menu, root);
'기술블로그' 카테고리의 다른 글
Component Driven Development (0) | 2023.02.20 |
---|---|
UI/UX (0) | 2023.02.15 |
JSON.stringfy (0) | 2023.02.14 |
Technical Questions (0) | 2023.02.10 |
agora-states-server (0) | 2023.02.09 |