add a id
attribute while visiting a tree using unist-util-visit
?
#88
-
in this blog, it shows this code: visit(tree, 'element', function (node) {
if ( node.tagName === 'h2' ) {
const id = parameterize(node.children[0].value);
node.properties.id = id;
}
}); i tried it, it doesn't work. mabye because it was for previous versions. i also tried doing files.forEach((file) => {
const tree = unified().use(remarkParse).parse(file.content)
visit(tree, (node) => {
if (node.type === 'heading') {
const slug = slugger.slug(node.children[0].value)
node.children = [
{
type: 'element',
tagName: `h${node.depth}`,
properties: { id: slug },
children: [{ type: 'text', value: title }],
},
]
console.log(JSON.stringify(node.children))
const noOfHastags = '#'.repeat(node.depth)
const href = `#${slug}`
const value = `${noOfHastags} ${node.children[0].value}`
lis.push({ href, value })
}
})
}) what should i do to edit a single attribute the reason i need this is because |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
You might notice from the reference code, and your code, that they are different. If you’re goal is to add HTML attributes, you are dealing with HTML, and you need to do things in that space: in rehype, working on hast. You are also doing some other things:
Last, I really recommend to stop using |
Beta Was this translation helpful? Give feedback.
-
used 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
}
})
}) |
Beta Was this translation helpful? Give feedback.
used
unist-util-visit
to addid
to headers. this blog was useful in understandingmdast
&hast
structure.