Problem 37

Count Tags Recursion Challenge

Given an HTML tag name, return the number of times that tag appears in the DOM. The function should traverse the DOM tree starting from document.body if no starting node is provided.

Node Structure

Each DOM node has the following properties useful for this problem:

  • node.nodeName — the tag name in uppercase (e.g. "DIV", "P", "SPAN").
  • node.childNodes — a list of the node's direct children (elements, text nodes, etc.).

Compare node.nodeName against tag.toUpperCase() to check for a match, then recurse into each child via node.childNodes.

Function Signature

tagCount(tag, node)

Parameters

  • tag — a string representing an HTML tag name (e.g. 'div', 'p', 'span').
  • node — (optional) a DOM node to start searching from. Defaults to document.body.

Output

Return a number representing how many elements with the given tag name exist in the DOM tree.

Constraints

  • The function must use recursion.
  • The tag argument is required; node is optional.
  • The function should accept at most two arguments.

Examples

// Given this DOM tree:
// <div>
//   <p>beep</p>
//   <div>
//     <p><span>blip</span></p>
//   </div>
//   <p>blorp</p>
// </div>

tagCount('p')    → 3
tagCount('div')  → 2
tagCount('span') → 1