fb55/htmlparser2

How do I add custom attributes to each node

Neil1223 opened this issue · 2 comments

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);
fb55 commented

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);