如何遍历特定div标签中的所有标头标签?我正在尝试自动在div标签中创建所有内容的文档结构树并将其放置在侧边栏菜单中...如果有易于使用的javascript库...我也希望采用这种方法,因为那样我就不会不需要编写任何JavaScript代码...
$( document ).ready( readyFn );
function readyFn( jQuery ) {
//alert("hey!");
var docmap = $("#docmap");
var body = $("#body");
docmap.append('<br>Some new content!');
var all = body.getElementsByTagName("h1, h2, h3, h4, h5, h6");
for (var i=0, max=all.length; i < max; i++) {
docmap.append(all[i].innerHtml);
}
}
#docmap {
background-color: #f0f0f0;
height: 100%;
width: 200px;
position: fixed;
}
#main {
margin-left: 200px;
position: 200px;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="docmap">
<ul>
<li> hello
<li> hi
<li> howdy
</ul>
</div>
<div id="main">
<h1>header1</h1>
<h2>header2 a</h2>
<h2>header2 b</h2>
<h1>header1 a</h1>
</div>
答案 0 :(得分:1)
使用find
获取元素,然后在它们上循环。
$( document ).ready( readyFn );
function readyFn( $ ) {
var docmap = $("#docmap");
var body = $("#body");
docmap.append('<br>Some new content!');
var all = body.find("h1, h2, h3, h4, h5, h6");
all.each(function(){
docmap.append(this.innerHTML);
});
}
#docmap {
background-color: #f0f0f0;
height: 100%;
width: 200px;
position: fixed;
}
#main {
margin-left: 200px;
position: 200px;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="docmap">
<ul>
<li> hello
<li> hi
<li> howdy
</ul>
</div>
<div id="main">
<h1>header1</h1>
<h2>header2 a</h2>
<h2>header2 b</h2>
<h1>header1 a</h1>
</div>