JavaScript 遍历文档生成目录结构
要遍历 HTML 文档并生成目录结构,你可以使用 JavaScript 来进行 DOM 操作和遍历。以下是一个简单的示例代码,演示了如何遍历文档中的标题元素(例如 <h1>
、<h2>
、<h3>
等),并根据它们的层次结构生成目录:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document Outline</title>
</head>
<body>
<!-- 示例文档 -->
<h1>Heading 1</h1>
<p>This is some content under Heading 1.</p>
<h2>Subheading 1.1</h2>
<p>This is some content under Subheading 1.1.</p>
<h2>Subheading 1.2</h2>
<p>This is some content under Subheading 1.2.</p>
<h3>Sub-subheading 1.2.1</h3>
<p>This is some content under S