Markdown header links with markdown-it

Date: 2022-12-04 | markdown | markdown-it | html |

Linking to a header

Most web browsers allow for linking to specific headers on a page provided a few things are true:

  • Header: an id attribute like id="HEADER-ID"
  • Url: ends with #HEADER-ID

This url will prompt the browser to jump to the header on the page with the matching id attribute, if it exists.

Header links with markdown-it

markdown-it is a popular npm library for converting markdown files to renderable HTML. This is a common method for building content-focused web pages and ensuring the data and views are decoupled.

However, markdown-it does not create id attributes on headers by default making it impossible to link to headers rendered via this method.

markdown-it header links with markdown-it-anchor

To solve this, we can use mardown-it-anchor. This library is a markdown-it plugin that specifically allows us to add id attributes to the rendered HTML.

Assuming you already have markdown-it working in your site, we can simply plug markdown-it-anchor into the render pipeline:

import markdownIt from "markdown-it"
import markdownItAnchor from "markdown-it-anchor"

// ...

const md = markdownIt()
    .use(markdownItAnchor)
const mdHtml = md.render(MARKDOWN)

Next Steps

This should enable you to link directly to header sections.

This is the same technique I'm using to render header links for my markdown files here on the site.

If you're interested in learning more about how I build websites, check out Up and Running with CloudSeed (F# / SvelteKit boilerplate)

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.