Generating HTML tags with IDs from Structured Text

Hi there!

We’re using the datocms-structured-text-to-html-string utility to convert content from a Structured Text field to HTML. I figured out how to add classes to HTML tags, but how do I add unique IDs to an HTML tag?

The use case I have in mind is linking to specific <h2 id="heading1/2/3/4/…"> tags from a table of contents.


Hello @Nico

It is possible that there is an exception for the “id” key as an argument, but can you verify if this aproach works?

    return renderNode('h2', { id: "heading1/2/3/4/…" }, ...);
1 Like

Hi @m.finamor,

Thanks! This works but doesn’t loop through the IDs, so that every <h2> tag has the same ID.

However, when I use the key property (which is hinted at in the docs) I can render the <h2> tags with unique IDs:

const renderOptions = {
    customNodeRules: [
      renderNodeRule(isHeading, ({ adapter: { renderNode }, key, children }) => {
        return renderNode(`h2`, { id: `heading-${key}` }, children)

The result then looks something like this:

<h2 id="heading-t-0">…</h2>
<h2 id="heading-t-3">…</h2>

This is not exactly what I was looking for, which is more like this:

<h2 id="heading-t-0">…</h2>
<h2 id="heading-t-1">…</h2>

However, I can work with it.
Thank you!

1 Like