简体   繁体   中英

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

How to iterate over all the header tags in a specific div tag? I'm trying to automatically create a document map tree of everything in my div tag and place it in a sidebar menu... If there's an easy to use javascript library... i would like that approach as well because then i wouldn't need to write any javascript code...

 $( 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>

Use find to get the elements and then loop over them.

 $( 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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