Objective

Create a Node instance method to count all the nodes under a given node, including itself.

Difficulty

Easy

Description

Suppose we have the following configuration of the DOM tree for a particular document:

A detailed DOM tree representation.
A detailed DOM tree representation.

We've seen this figure before in the HTML DOM — Basics chapter, but for a different reason. There we studied it to understand the idea of a DOM tree, that's created internally by the browser after parsing a given document.

Now, we're interested in figuring out the total number of nodes under a given node, including itself.

The idea is really simple — we can just count the number of boxes in the figure originating from a given box to get our answer.

So talking about the root document node, there are a total of 23 nodes under it, including itself. Right?

This is the node count of the document node.

Similarly, if we were to repeat this exact same process, but replacing document with <body>, we'd get 12. Or replacing it with <head>, we'd get 7. Or with <p>, we'd get 2. Or with the comment node, we'd simply get 1.

In short, the node count of the a given node is the sum of the node counts of each of its children nodes, plus 1 (for itself).

In this exercise, you have to define a getNodeCount() instance method on the Node interface that returns back the node's node count, as detailed above.

Shown below are a couple of examples, for the following HTML document whose DOM tree is shown in the figure above:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>Learning the DOM</title>
</head>
<body>
   <!--A simple comment-->
   <h1>Learning the <b>DOM</b></h1>
   <p>The DOM is simple.</p>
</body>
</html>
// Assuming that the getNodeCount() method has been defined.
undefined
document.getNodeCount()
23
document.body.getNodeCount()
12
document.head.getNodeCount()
7
document.body.children[1].getNodeCount() // <p> element
2
document.body.childNodes[1].getNodeCount() // The comment
1