Basic example of how to add a node? #374
Unanswered
NullVoxPopuli
asked this question in
Q&A
Replies: 2 comments 5 replies
-
|
@NullVoxPopuli You can try this way, perhaps there is a more elegant solution const posthtml = require('posthtml')
const html = `<a>test1</a><span><a>test2</a></span><a>test1</a>`;
const plugins = [
function(tree) {
tree.walk(node => {
if (node.tag === 'a' && (node.attrs === undefined || node.attrs.skip === undefined)) {
node.attrs = {
skip: true
}
return {
tag: false,
content: [
{tag: 'a', content: 'test0', attrs: {skip: true}},
node
]
}
}
return node;
});
tree.match({tag: 'a'}, node => {
delete node.attrs.skip;
return node;
})
return tree;
}
]
const options = {}
posthtml(plugins)
.process(html, options)
.then((result) => console.log(result.html)) |
Beta Was this translation helpful? Give feedback.
4 replies
-
|
Have the same issue, I want to add a new node. Maybe add some method for creating a node to the core library? More "legal" way. By now, I use a class. like this // Or better use a plain object?
class Node {
constructor(tag, attrs, content) {
this.tag = tag;
this.attrs = attrs;
this.content = content;
}
}
posthtml().use((tree) => {
tree.match({ tag: 'p' }, (node) => {
node.content ??= [
new Node('span', { class: 'some' }, ['text']),
];
return node;
})
}); |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

Uh oh!
There was an error while loading. Please reload this page.
-
I'm wanting to prepend a
linktag before all existinglinktags.I've been reading the README, some tests, etc -- haven't found such a capability.
Is this possible? how would you do it?
Beta Was this translation helpful? Give feedback.
All reactions