DOM Tree Traversals

Exercise instructions

Exercise Overview

In this exercise you are going to traverse an unordered list that has several nested lists inside it. Your task is to count the number of descendant <li> elements of every <li> element in the list and add the count to each element. You must skip adding counts numbers to the <li> elements that have no descendants.

The before and after of the lists is shown in the image below. Notice how on the right side there are numbers in parentheses after many list items. Those are the counts of the descendant <li> elements inside that particular list item. Notice how Animals list item has 17 descendant list item, which include all the list items, as in this example all other list items are descendants of Animals list item in the DOM.

before and after

The before and after of the lists

Solving the exercise

Start by making sure you are in your local clone of the Git repository, and in its exercises/03_javascript/ex3 directory. Then:

  • Create a file called dom-tree.js and implement the exercise.
  • You can find the HTML in the index.html file inside this directory. Open this file in your browser. Remember to open the developer console to see any errors in your code. DO NOT EDIT THIS FILE!
  • Every time you are ready to test your code follow these steps:
    1. Save your code
    2. Reload the index.html page
    3. If something went wrong you are likely to see some error messages inside the developer console. Fix the errors and try again from the first step.
    4. If everything works as expected your list should now have descendant counts visible. Make sure the counts are correct.

Your code will be tested with different list and data. DO NOT assume anything about the depth of nesting or the number of list items!

Hints

  • Empty space does not affect the grader. Only text matters. DO NOT rely on the amount of indentation or the position of line changes in the HTML!
  • element.getElementsByTagName(), element.getElementsByClassName(), and element.querySelectorAll() return all matching elements even if they are not the immediate children of the element. This is useful in calculating element's descendants.
  • DOM's NodeLists, which is returned by e.g., querySelectorAll(), can be looped through with forEach() method
  • Remember that text and whitespace are represented by Text node(s) which can be manipulated independently of other nodes such as elements. The text inside these nodes can be accessed with node.nodeValue and node.data.

Remember to commit dom-tree.js and push the changes to your Git repository before you submit your work in Plussa.

Submitting Your Project to Plussa

PLEASE NOTE: You should copy-paste the git@.... url, not the https://... url

Did you remember git add - git commit - git push?