Back to the lesson

Count descendants

importance: 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.

Demo in new window

Open the sandbox for the task.

Let’s make a loop over <li>:

for (let li of document.querySelector('li')) {

In the loop we need to get the text inside every li. We can read it directly from the first child node, that is the text node:

for (let li of document.querySelector('li')) {
  let title =;

  // title is the text in <li> before any other nodes

Then we can get the number of descendants li.getElementsByTagName('li').

Open the solution in the sandbox.