domhandler Build Status

The DOM handler (formally known as DefaultHandler) creates a tree containing all nodes of a page. The tree may be manipulated using the domutils library.

Usage

  1. var handler = new DomHandler([ <func> callback(err, dom), ] [ <obj> options ]);
  2. // var parser = new Parser(handler[, options]);

Available options are described below.

Example

  1. var htmlparser = require("htmlparser2");
  2. var rawHtml = "Xyz <script language= javascript>var foo = '<<bar>>';< / script><!--<!-- Waah! -- -->";
  3. var handler = new htmlparser.DomHandler(function (error, dom) {
  4. if (error)
  5. [...do something for errors...]
  6. else
  7. [...parsing done, do something...]
  8. console.log(dom);
  9. });
  10. var parser = new htmlparser.Parser(handler);
  11. parser.write(rawHtml);
  12. parser.end();

Output:

  1. [{
  2. data: 'Xyz ',
  3. type: 'text'
  4. }, {
  5. type: 'script',
  6. name: 'script',
  7. attribs: {
  8. language: 'javascript'
  9. },
  10. children: [{
  11. data: 'var foo = \'<bar>\';<',
  12. type: 'text'
  13. }]
  14. }, {
  15. data: '<!-- Waah! -- ',
  16. type: 'comment'
  17. }]

Option: normalizeWhitespace

Indicates whether the whitespace in text nodes should be normalized (= all whitespace should be replaced with single spaces). The default value is “false”.

The following HTML will be used:

  1. <font>
  2. <br>this is the text
  3. <font>

Example: true

  1. [{
  2. type: 'tag',
  3. name: 'font',
  4. children: [{
  5. data: ' ',
  6. type: 'text'
  7. }, {
  8. type: 'tag',
  9. name: 'br'
  10. }, {
  11. data: 'this is the text ',
  12. type: 'text'
  13. }, {
  14. type: 'tag',
  15. name: 'font'
  16. }]
  17. }]

Example: false

  1. [{
  2. type: 'tag',
  3. name: 'font',
  4. children: [{
  5. data: '\n\t',
  6. type: 'text'
  7. }, {
  8. type: 'tag',
  9. name: 'br'
  10. }, {
  11. data: 'this is the text\n',
  12. type: 'text'
  13. }, {
  14. type: 'tag',
  15. name: 'font'
  16. }]
  17. }]

Option: withDomLvl1

Adds DOM level 1 properties to all elements.

Option: withStartIndices

Indicates whether a startIndex property will be added to nodes. When the parser is used in a non-streaming fashion, startIndex is an integer indicating the position of the start of the node in the document. The default value is “false”.

Option: withEndIndices

Indicates whether a endIndex property will be added to nodes. When the parser is used in a non-streaming fashion, endIndex is an integer indicating the position of the end of the node in the document. The default value is “false”.