How to automatically add unique ID’s to H2 tags for content deep-linking

Learn how to add direct links to H2 so that you can point to specific parts of your articles.

In general, for most of my blog posts, I have the following structure:

<h1>Main topic of the post</h1>
    <h2>Subtopic 1</h2>
    <h2>Subtopic 2</h2>
    <h2>Subtopic 3</h2>
    ....

I've needed a way to point to a specific h2. For anchors, you can do that by pointing to a URL followed by the ID of an element from the page:

<h2 id="anchor-name">The title where you want to jump</h2>
<a href="my-blog-url.com/pots-tile#anchor-name">
    Jump to the part of the page with the ID of โ€œanchor-nameโ€  
</a>

The whole idea was to be able to do this without manually adding ID's to each secondary title I have on each page.

Initially, I tried to make this somehow with a combination of CSS counters and maybe the content property of before and/or after pseudo-classes.

When that solution failed, I've ended up with the below JS script:

document.querySelectorAll('article.post h2').forEach(h => {
  //create id from heading text
  var id =
    h.getAttribute('id') ||
    h.innerText
      .toLowerCase()
      .replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')
      .replace(/ +/g, '-')

  //add the id to the heading
  h.setAttribute('id', id)

  //append parent class to heading
  h.classList.add('anchor-heading')

  //create an anchor
  let anchor = document.createElement('a')
  anchor.className = 'anchor-link'
  anchor.href = '#' + id
  anchor.innerText = ' #'

  //append anchor after heading text
  h.appendChild(anchor)
})

What the script does is to pick all the h2 elements we have on the page. If that element does not yet has an ID attribute give it one made from the words of that title separated by a dash character. And at the end appends a # character so that we can easily point to it.

For example, checkout this link that points directly to why should I use HSL colors over other formats such as RGB or Hexa.

By the way you can also create links and scroll to any text fragment in an HTML page without adding unique IDs

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

๐Ÿ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X