繁体   English   中英

如何遍历特定 div 标签中的所有标题标签?

[英]How to iterate over the all the header tags in a specific div tag?

如何遍历特定 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>

使用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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM