insert img
inside of h2
?
#139
Unanswered
deadcoder0904
asked this question in
Q&A
Replies: 1 comment 14 replies
-
You can remove most lines of your code, they are not needed. For example, you are not dealing with mdast, so you don‘t have to import those types. And, you don’t need all those tools. You especially don’t need You also use TypeScript but cast things to Instead, I recommend using the visitor pattern to traverse the tree: https://unifiedjs.com/learn/recipe/tree-traversal/. It can do everything you need, is fast, and is simple. To illustrate: import {visit} from 'unist-util-visit'
/** @type {import('hast').Root} */
const tree = {}
visit(tree, function (node, index, parent) {
if (
node.type === 'element' &&
node.tagName === 'h2' &&
typeof index === 'number' &&
parent
) {
const next = parent.children[index + 1]
if (next && next.type === 'element' && next.tagName === 'img') {
node.children.push(next)
parent.children.splice(index + 1, 1)
}
}
}) |
Beta Was this translation helpful? Give feedback.
14 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
i have a html block that looks like:
i want the
img
to be inside ofh2
like:the
h2
&img
is inside mdx like:i tried using:
but for some reason, i'm unable to read selectors from
select
&selectAll
... they both come empty[]
. my actual selector ish2 > img
but i can't get it to work.so i gave that up after trying 2 days every which way.
then now i've recently downloaded
rehype-rewrite
but unable to figure out, how to put the node inside:no matter how many times i work with
unified
&rehype
, it still confuses me.i did read the explore & learn again but no luck.
edit: i found a solution but definitely don't prefer it. insert
img
from insiderehype-rewrite
by calculatingh2
's so every image is in array[img1, img2]
& they get inserted but this requires some calculation as i don't add image after everyh2
but only some of them... which can be calculated too but still not preferred if i can do it in an easy way.Beta Was this translation helpful? Give feedback.
All reactions