A PostHTML helper plugin that provides a better API for working with tag attributes.
Usage
import posthtml from 'posthtml';
import parseAttrs from 'posthtml-attrs-parser';
posthtml()
.use(function (tree) {
const div = tree[0];
const attrs = parseAttrs(div.attrs);
attrs.style['font-size'] = '15px';
attrs.class.push('title-sub');
div.attrs = attrs.compose();
})
.process('<div class="title" style="font-size: 14px">Hello!</div>')
.then(function (result) {
console.log(result.html);
});
Both ESM and CJS exports are provided, you can use the plugin in CJS too:
const posthtml = require('posthtml');
const parseAttrs = require('posthtml-attrs-parser');
Attributes
Only style
and class
attributes are parsed by default (as object and array, respectively). For other attributes, the parsing rules should be specified (see Custom parsing rule below).
Default attributes
style
<div style="color: red; font-size: 14px; color: blue"></div>
const attrs = parseAttrs(div.attrs);
console.log(attrs.style);
class
<div class="title title-sub"></div>
const attrs = parseAttrs(div.attrs);
console.log(attrs.class);
Custom parsing rule
You may also define the parsing rule for other attributes.
Array-like attribute
<div data-ids="1 2 4 5 6"></div>
const attrs = parseAttrs(div.attrs, {
rules: {
'data-ids': {
delimiter: /\s+/,
glue: ' '
}
}
});
console.log(attrs['data-ids']);
console.log(attrs.compose()['data-ids']);
Object-like attribute
<div data-config="TEST=1;ENV=debug;PATH=."></div>
const attrs = parseAttrs(div.attrs, {
rules: {
'data-config': {
delimiter: ';',
keyDelimiter: '=',
glue: '; ',
keyGlue: ' = '
}
}
});
console.log(attrs['data-config']);
console.log(attrs.compose()['data-config']);