FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Hard

Get Element By Tag Name Hierarchy

45mins

Implement a function getElementByTagNameHierarchy(root, tags) that returns all DOM elements matching a specific hierarchy of tag names.

The function should:

  • Accept a root element to search within.
  • Accept an array of tag names representing the hierarchy to match.
  • Return all elements whose parent-child structure matches the given hierarchy.
  • Handle deeply nested elements and multiple matching branches.

Examples

const doc = new DOMParser().parseFromString(` <div> <ul> <li><span>Item 1</span></li> <li><span>Item 2</span></li> </ul> <ul> <li><p>Other</p></li> </ul> </div>`, 'text/html'); getElementByTagNameHierarchy(doc.body, ['ul', 'li', 'span']); // returns [<span>Item 1</span>, <span>Item 2</span>]

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests