후손 노드 개수 세기
중요도: 5
ul
과 li
노드로 구성된 트리 구조 문서가 있다고 가정해봅시다.
li
노드 전체를 대상으로 아래와 같은 작업을 하려 합니다. 조건을 만족시킬 수 있는 코드를 작성해보세요.
li
노드 안에 있는 텍스트를 출력li
노드 아래에 있는 모든<li>
태그의 개수를 출력
Let’s make a loop over <li>
:
for (let li of document.querySelectorAll('li')) {
...
}
In the loop we need to get the text inside every li
.
We can read the text from the first child node of li
, that is the text node:
for (let li of document.querySelectorAll('li')) {
let title = li.firstChild.data;
// title is the text in <li> before any other nodes
}
Then we can get the number of descendants as li.getElementsByTagName('li').length
.