PostHTML Attrs Parser
PostHTML helper that gives a better API to work with tag's attrs.
Usage
var posthtml = require('posthtml'),
parseAttrs = require('posthtml-attrs-parser');
posthtml()
.use(function (tree) {
var div = tree[0],
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);
});
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
var attrs = parseAttrs(div.attrs);
console.log(attrs.style);
class
var attrs = parseAttrs(div.attrs);
console.log(attrs.class);
Custom parsing rule
You can also define the parsing rule for other attributes.
Array-like attribute
var attrs = parseAttrs(div.attrs, {
rules: {
'data-ids': {
delimiter: /\s+/,
glue: ' '
}
}
});
console.log(attrs['data-ids']);
console.log(attrs.compose()['data-ids']);
Object-like attribute
var attrs = parseAttrs(div.attrs, {
rules: {
'data-config': {
delimiter: ';',
keyDelimiter: '=',
glue: '; ',
keyGlue: ' = '
}
}
});
console.log(attrs['data-config']);
console.log(attrs.compose()['data-config']);