valeriangalliat / markdown-it-anchor

A markdown-it plugin that adds an `id` attribute to headings and optionally permalinks.
The Unlicense
291 stars 72 forks source link

Query: How do I attach a class to the header element? #132

Closed realChakrawarti closed 2 months ago

realChakrawarti commented 2 months ago

Thank you for the amazing work.

I went through the documentation/README but couldn't find a way to attach a class to the header element where id is injected.

Here is my existing implementation:

  md.use(anchor, {
    tabIndex: false,
    slugify: (s: string) => slugify(s),
    permalink: anchor.permalink.headerLink(),
  });

which outputs as expected.

<h2 id="example-id"><a class="header-anchor" href="#example-id">Example ID</a></h2>

But I want something like:

<h2 id="example-id" class="hardcoded"><a class="header-anchor" href="#example-id">Example ID</a></h2>

The reason for this to add scroll-margin-top, as due to fixed header, the heading element remains hidden.

If there any workaround to do the same, please do let me know. Thanks.

valeriangalliat commented 2 months ago

Hi!

There's no such option at the moment however you can leverage the callback argument to implement that easily!

The callback gets passed the markdown-it Token object for every heading element that gets processed, so you can use that to append a class to it:

   md.use(anchor, {
     tabIndex: false,
     slugify: (s: string) => slugify(s),
     permalink: anchor.permalink.headerLink(),
+    callback: (token) => token.attrJoin('class', 'hardcoded'),
   });

Cheers :)

realChakrawarti commented 2 months ago

This worked. Thank you. Closing the issue.