前一段时间做的面试题的简单回顾, 通过遍历文档创建标题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.content {
font-weight: bolder;
font-style: italic;
}
div {
display: inline-block;
}
#menu {
width: 400px;
float: right;
}
</style>
</head>
<body>
<div id="content">
<h1>标题 1</h1>
<div class="content">内容 1</div>
<h2>标题 2</h2>
<div class="content">内容 2</div>
<h1>标题 3</h1>
<div class="content">内容 3</div>
<h2>标题 4</h2>
<div class="content">内容 4</div>
<h3>标题 5</h3>
<div class="content">内容 5</div>
<h1>标题 6</h1>
<div class="content">内容 6</div>
<h2>标题 7</h2>
<div class="content">内容 7</div>
</div>
<div id="menu">
<ul id="menu-ul">
<li class="menu-li"><a href="#">例标题1</a></li>
</ul>
</div>
<script>
function createMenu() {
// let div = document.getElementById("Content")[0];
// for (let i = 0, len = div.childNodes.length; i < len; i++) {
// }
let h = document.querySelector("#content").querySelectorAll("h1,h2,h3,h4,h5,h6");
let ul = document.getElementById("menu-ul");
let s = "";
for (let i = 0, len = h.length; i < len; i++) {
ul.innerHTML += `<li class="menu-li"><a href="#"><${h[i].nodeName}>${h[i].firstChild.nodeValue}<${h[i].nodeName}/></a></li>`;
}
}
window.onload = createMenu();
</script>
</body>
</html>