rehype plugin to add id
s to all elements based on their content, assigning each a unique id.
This package is a unified (rehype) plugin to add id
s to all elements.
It looks for all elements (<h1>
, <p>
, <span>
, etc.) that do not yet have id
s
and adds id
attributes to them based on the text they contain.
The algorithm that does this is uuid-by-string
.
This plugin is useful for creating anchor links for every element in your document. For example, it enables adding comments or annotations to specific parts of a document. Additionally, it is helpful for generating a table of contents, as it allows linking to every section in the document.
A different plugin, rehype-slug
, adds id
s to headings. It looks for headings (so <h1>
through <h6>
) that do not yet have ids and adds id attributes to them based on the text they contain.
This package is ESM only. In Node.js (version 16+), install with npm:
npm install rehype-id
Say we have the following file example.html
:
<h1 id="some-id">Lorem ipsum</h1>
<h2>Dolor sit amet 😪</h2>
<p>Hello world!</p>
<span>Hello world!</span>
…and our module example.js
looks as follows:
import {read} from 'to-vfile'
import {rehype} from 'rehype'
import rehypeId from 'rehype-ud'
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeId)
.process(await read('example.html'))
console.log(String(file))
…then running node example.js
yields:
<h1 id="some-id">Lorem ipsum</h1>
<h2 id="h2-2e3b53f0">Dolor sit amet 😪</h2>
<p id="p-d3486ae9">Hello world!</p>
<span id="span-d3486ae9">Hello world!</span>
Transform (Transformer
).
-
prefix
(string
, default:''
) — prefix to add in front ofid
s -
skipHeadings
(boolean
, default:true
) — skip adding id to headings
Use of rehype-id
can open you up to a cross-site scripting (XSS)
attack as it sets id
attributes on headings, which causes what is known
as “DOM clobbering”.
Please use rehype-sanitize
and see its
Example: headings (DOM clobbering) for information on
how to properly solve it.
-
rehype-slug
— addid
s to headings based on their content -
rehype-autolink-headings
— add links to headings with IDs back to themselves
MIT © Daniel Castillo strongly based on rehype-slug
.