Looking to implement a bookmark system using the headings within my HTML document, based on heading hierarchy. Unfortunately, my attempts have not been successful so far. https://i.stack.imgur.com/CdXjw.png
I envision my bookmarks looking something like this with corresponding links:
https://i.stack.imgur.com/7vBUb.png
Here's the snippet of my HTML code:
<style>
#bookMark {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
<div id="bookMark">
<b>Book Mark: </b>
</div>
<h1> This is 1st main Heading1 </h1>
<h2> This is h2 under h1 </h2>
<h3> This is h3 under h1 and h2 </h3>
<h2> This is h2 </h2>
<h3> This is h3</h3>
<h1> This is 2nd main Heading1 </h1>
<h2> This is h2 under h1 </h2>
<script src="dom.js"> </script>
This is how my script code looks:
var heading1 = document.getElementsByTagName('h1');
var heading2 = document.getElementsByTagName('h2');
for(var i = 0; i < heading1.length; i++){
var para = document.createElement("p");
para.innerHTML = document.getElementsByTagName('h1')[i].innerHTML;
document.getElementById("bookMark").appendChild(para);
for(var j = 0; j < heading2 .length; j++){
var para = document.createElement("p");
para.innerHTML = " "+ document.getElementsByTagName('h2')[j].innerHTML;
document.getElementById("bookMark").appendChild(para);
}
}
The current output does not maintain the hierarchy correctly: https://i.stack.imgur.com/Zc1Gf.png