H Tags and Auto-Constructing an Anchor Index

Origin Story

I got a fairly dense Word document that needed to go online in way that people could more easily navigate. After checking it out, it appeared we had a large number of sections but we were lucky in that they were designated by H tags of various levels.

Now I could have gone through and added IDs to each H tag by hand but my masochism doesn’t run that way. The challenge was now to see if we couldn’t do this automatically with javascript.

Build It

It ended up being more succinct than anticipated and will undoubtedly be used again in other scenarios. I commented it up below to explain things.

let headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6")//get all the H tags
let i = 1;
let indexHtml = '';
let indexHolder = document.getElementById('index');//get my #index div that I made
headers.forEach(function(header) {
  header.id = "header-" + i;//give each H tag an unique ID
  indexHtml = indexHtml + '<li><a href="#header-' + i + '">'+header.innerHTML+'</a></li>' ;//make the index HTML
indexHolder.innerHTML = indexHtml;//put the html in the #index div

The other thing to consider is that maybe you can’t use javascript on the site. That’s ok, run it like this and then inspect element and copy the results. Now you can paste that into any place that takes HTML and you’re good to go.

See the Pen
health hub index
by Tom (@twwoodward)
on CodePen.