Making an Index Using Javascript

Working with a faculty member we had a rather long page that was originally written in Google Docs. It had many sections that were (mostly) designated by H tags of various denominations. The goal was to and put it on a website quickly build an index of anchor links. I did not wish to do the index portion by hand.

With javascript things like this are relatively pleasant. You can see the whole thing in this codepen but I’ll break it down a bit below.

First we can get all the H tags with querySelectorAll.

let headers = document.querySelectorAll("h2, h3, h4, h5, h6")

I can console.log(headers) and I’ll see a NodeList of all the headers it found. I tend to work console.log all my variables as I go just to make sure it’s really happening the way I think it is.

My next move is to add an id to each of these headers so that we can navigate to them via anchor links. with this forEach loop each header will get an id of header-whatever number we’re on in the loop.

let i = 1;
headers.forEach(function(header) {
  header.id = "header-" + i;
  ++i;
});

Now that I have headers that I can link to as anchor links, I need to build the index and put it somewhere.

In this case it was easy for me to add a div to the source manually so I did. That will be where my index ends up.

    I’ll get that div as a destination.

    let indexHolder = document.getElementById('index');
    

    I’ll assign a variable (indexHtml) to hold a string of HTML which will be all the li tags with the links and titles.

    We’ll go back to our forEach (cleaned of other stuff for clarity) loop and use it to build out that HTML.

    let i = 1;
    let indexHtml = '';
    headers.forEach(function(header) {
      indexHtml = indexHtml + '<li><a href="#header-' + i + '">'+header.innerHTML+'</a></li>' ;
      ++i;
    });//
    indexHolder.innerHTML = indexHtml;
    

    Now that we have the string, we can assign it as the innerHTML of the index div we created earlier.

    indexHolder.innerHTML = indexHtml;
    

    The whole thing looks like this.

    let headers = document.querySelectorAll("h2, h3, h4, h5, h6")
    let i = 1;
    let indexHtml = '';
    let indexHolder = document.getElementById('index');
    headers.forEach(function(header) {
      header.id = "header-" + i;
      indexHtml = indexHtml + '<li><a href="#header-' + i + '">'+header.innerHTML+'</a></li>' ;
      ++i;
    });//
    indexHolder.innerHTML = indexHtml;
    
    

    Comments on this post

    No comments.

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Trackbacks and Pingbacks on this post

    No trackbacks.

    TrackBack URL