Skip to content

add a id attribute while visiting a tree using unist-util-visit? #88

Discussion options

You must be logged in to vote

used unist-util-visit to add id to headers. this blog was useful in understanding mdast & hast structure.

import { visit } from 'unist-util-visit'

const processor = await unified()
	.use(remarkParse, { fragment: true })
	.use(remarkRehype)
	.use(rehypeDocument, {
		title,
		link,
	})
	.use(() => (tree) => {
		visit(tree, 'element', (node) => {
			const headers = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
			if (headers.includes(node.tagName)) {
				const title = toString(node.children)
				const slug = slugger.slug(title)
				node.properties.id = slug
			}
		})
	})

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
8 replies
@deadcoder0904
Comment options

@wooorm
Comment options

@deadcoder0904
Comment options

@wooorm
Comment options

@deadcoder0904
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by deadcoder0904
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants