돌아가기
이 글은 다음 언어로만 작성되어 있습니다. عربي, English, Español, 日本語, Русский, 简体中文. 한국어 번역에 참여해주세요.

Count descendants

중요도: 5

There’s a tree structured as nested ul/li.

Write the code that for each <li> shows:

  1. What’s the text inside it (without the subtree)
  2. The number of nested <li> – all descendants, including the deeply nested ones.

새 창에서 데모 보기

샌드박스를 열어 정답을 작성해보세요.

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.

샌드박스를 열어 정답을 확인해보세요.