FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Hard

Table of Contents

45mins

Implement a function generateTOC(root) that constructs a Table of Contents (TOC) from an HTML document.

The function should:

  • Accept a root element to search within.
  • Identify heading elements (<h1> to <h6>) in the order they appear.
  • Return an array of objects with level (heading level) and text (heading content).

Examples

const doc = new DOMParser().parseFromString(` <div> <h1>Introduction</h1> <h2>Background</h2> <h2>Goals</h2> <h1>Conclusion</h1> </div>`, 'text/html'); generateTOC(doc.body); // [ // { level: 1, text: 'Introduction' }, // { level: 2, text: 'Background' }, // { level: 2, text: 'Goals' }, // { level: 1, text: 'Conclusion' } // ]

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests