rehype-id

1.0.2 • Public • Published

rehype-id

Downloads Size

rehype plugin to add ids to all elements based on their content, assigning each a unique id.

Contents

What is this?

This package is a unified (rehype) plugin to add ids to all elements. It looks for all elements (<h1>, <p>, <span>, etc.) that do not yet have ids and adds id attributes to them based on the text they contain. The algorithm that does this is uuid-by-string.

When should I use this?

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 ids 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.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install rehype-id

Use

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>

Documentation

Returns

Transform (Transformer).

Options

  • prefix (string, default: '') — prefix to add in front of ids

  • skipHeadings (boolean, default: true) — skip adding id to headings

Security

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.

Related

License

MIT © Daniel Castillo strongly based on rehype-slug.

Package Sidebar

Install

npm i rehype-id

Weekly Downloads

8

Version

1.0.2

License

MIT

Unpacked Size

8 kB

Total Files

5

Last publish

Collaborators

  • dcastillogi