0

I'm new to JavaScript, and for school I have to automatically make every <\h1> on my page generate into an "ol" with in every "li" a link to the place on my page where that header is placed so in the end I have a table of contents with links on every "li". So I should be able to just write text and not worry about the table of contents. Is there a way to do this without using too complixated code? And preferably not very long so I can understand it.

e.g.

<h1 id="h1-01">Title 1<\h1>
<h1 id="h1-02">Titel 2<\h1>
<h1 id="h1-03">Titel 3<\h1>
<h1 id="h1-04">Titel 4<\h1>

Make this generate like:

<ol>
<li><a href="h1-01">Title 1</a></li>
<li><a href="h1-02">Title 2</a></li>
<li><a href="h1-03">Title 3</a></li>
<li><a href="h1-04">Title 4</a></li>
</ol>

edit: I don't want anyone to make all of my homework, this is just a tiny tiny part of the homework even. What I want to know is how do I make an organized list with list items in javascript without too complicated code. I already found a way to put every header text in a variable. This is what I have

function generate(){
var titels = new Array();
for(var i = 1;i<10;i++){
var test = 'h1-0'+ i;
    titels[i] = document.getElementById(test).textContent;  
}
}
-->
</script>

The only problem is now that I have to make a list with these variables, but I haven't found anything usefull on the internet, everything that I've found uses Jquery ir is specific for someone's problem. I would also like a way to count the amount of headers I'm using but tthat's another question. Is it actually even possible to have code that gets literally implemented like I'm writing it?

like:

html.write("<ol>");

for(var i = 1, i<10,i++){

html.write("<il>" + titels[i] +  "<\il>");

}

html.write("<\ol>")
user3052776
  • 49
  • 1
  • 2
  • 6

2 Answers2

0

I'm not going to do your homework, but will point you in a good direction.

Try building an object containing the id and the title of each entry. From there, you can use that object to build practically anything, including an ordered list.

Of course, you can hard-rewrite the h1 tags into list items, but that's just not the proper way to do it and not something you should learn from.

Shomz
  • 37,421
  • 4
  • 57
  • 85
0

A start hint: You could do it with the help of jquery.

Like this HTML:

 <ol id=contents></ol>

   <h1>Test</h1>
      bla bla 

      <h1> Test2 </h1>
      Ble ble ble

Jquery:

 $(document).ready(function(){
     $("h1").each(function(){
         $("#contents").append("<li>" + $(this).html() + "</li>");
     });
 });
Philip G
  • 4,098
  • 2
  • 22
  • 41