πŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

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 *