I am using 'htmlparser2.parseDocument' parse htmlString.
I want to add a property to every Node, such as:
{
type: 'tag',
parent: xxx,
prev: [Text],
next: [Text],
startIndex: null,
endIndex: null,
children: [],
name: 'import',
attribs: [Object],
__custome__: 'xxxx' // custome attrib
},
This problem has been solved by modify the prototype:
const htmlparser2 = require('htmlparser2');
const { DomHandler } = require('domhandler');
var htmlString = `xxxxx`;
const addNode = DomHandler.prototype.addNode;
DomHandler.prototype.addNode = function (node) {
node.__custom__ = 'test';
addNode.call(this, node);
};
var handler = new DomHandler(undefined, {});
new htmlparser2.Parser(handler, {}).end(htmlString);
console.log(handler.root.children);
If you don't want to override the prototype, you can also extend the class:
const htmlparser2 = require('htmlparser2');
const { DomHandler } = require('domhandler');
var htmlString = `xxxxx`;
class CustomHandler extends DomHandler {
addNode(node) {
node.__custom__ = 'test';
super.addNode(node);
}
}
var handler = new CustomHandler(undefined, {});
new htmlparser2.Parser(handler, {}).end(htmlString);
console.log(handler.root.children);
Owner Name | fb55 |
Repo Name | htmlparser2 |
Full Name | fb55/htmlparser2 |
Language | TypeScript |
Created Date | 2011-08-27 |
Updated Date | 2023-03-19 |
Star Count | 3793 |
Watcher Count | 50 |
Fork Count | 370 |
Issue Count | 4 |
Issue Title | Created Date | Updated Date |
---|