[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/tree-info [Back]  [Original]

Count descendants
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Count descendants

    importance: 5

    Theres a tree structured as nested ul/li.

    Write the code that for each <li> shows:

    1. Whats 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 a sandbox for the task.

    solution

    Lets 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.

    Open the solution in a sandbox.


    Web Proxy Viewer  |  New URL  |  Original Page