PostHTML plugin to add/modify tags and attributes
npm install posthtml-transformPostHTML plugin to add/modify tags attributes.
``js`
posthtml([
transform({ attr: 'fill', value: 'red' })
]);
Input
`xml`
Output
`xml`
`sh`
npm install posthtml-transform
`js
const { readFileSync } = require('fs');
const posthtml = require('posthtml');
const transform = require('posthtml-transform');
const input = readFileSync('input.html');
posthtml()
.use(transform(options))
.process(input)
.then(({ html }) => {
console.log(html);
});
`
Plugin accepts one or array of transformers. Transformer is an object with following fields:
- attr - name of tag attribute to modify. If doesn't exists it will be created. Should be used in combination with value.value
- - attribute value to set. Should be used in combination with attr.tag
- - tag name to set. Should be used in combination with selector (or without, if you want to rename all tags :).selector
- (optional, * by default) - CSS selector to find nodes. If not presented all nodes will be selected. div
Complete list of supported selectors see on posthtml-match-helper documentation.
Here is a short list:
- Tags .#id
- Ids ..class
- Classes , .class1.class2.[attr=value]
- Attributes , [attr!=value] etc.path, .class, #id
- Multiple selectors .g path
Nested selectors (, g > path) are not supported.
Example
`jsstroke
transform({ attr: 'fill', value: 'red' }); // add fill="red" to all nodes
transform({ attr: 'fill', value: 'red', selector: 'path' }); // add fill="red" only to paths
transform({ attr: 'stroke', value: 'black', selector: '#logo' }); // add attr to node with id="logo"`
transform({ selector: 'g', tag: 'symbol' }); // rename all
It is also possible to pass URL query params string to plugin. It will be parsed and converted to transformer params, e.g:
`js`
transform('fill=red'); // => { attr: 'fill', value: 'red' }
transform('fill=red&20path'); // => { attr: 'fill', value: 'red, selector: 'path' }
Parameter value has following syntax: attr_name=attr_value optional_selector.fill=red&stroke=black
Parameters can be combined, eg .
Examples:
```
fill=red
fill=red path
fill=red .class
fill=red #id, black .class
fill=red #id&stroke=black .class