Description

In web applications, elements are often deeply nested.
You are given a root DOM node and a string representing a class hierarchy separated by > symbols.

Write a function that returns the last matching element in the DOM that satisfies the full class hierarchy path.


Example

<div id="root">
<div class="a">
<div class="b">
<div class="c" id="target1"></div>
<div class="c" id="target2"></div>
</div>
</div>
</div>
getByClassNameHierarchy(document.getElementById("root"), "a>b>c");

Output:

<div class="c" id="target2"></div>

Function Signature

function getByClassNameHierarchy(root, classes)

Parameters

  • root — a DOM element (the starting node)
  • classes — a string representing class hierarchy like "a>b>c"

Return

  • The last matching element that matches the full hierarchy
  • Returns an empty array [] if no match is found

Constraints

  • The hierarchy levels are separated by '>'
  • You should traverse depth-wise in the DOM
  • The result should be the last matching descendant
  • Should not throw an error for invalid input