node.js - 用jsdom来解析一个HTML片段

jsf

2018-05-11T06:28:19Z||2018-05-11T06:28:19Z

安装:

yarn add jsdom

使用:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const dom = new JSDOM('<hi prop1="val" prop2="val"> hello <child prop="val">child content</child> world </hi>', 'text/html');
const document = dom.window.document;
const src = document.body.firstElementChild;
console.log(src.outerHTML);
console.log('----');
const nodes = src.childNodes;
for (let i = 0; i < src.childNodes.length; i++) {
  const node = nodes.item(i);
  console.log(`Type: ${node.nodeType}, Value: ${node}`);
}

输出:

<hi prop1="val" prop2="val"> hello <child prop="val">child content</child> world </hi>
----
Type: 3, Value: [object Text]
Type: 1, Value: [object HTMLUnknownElement]
Type: 3, Value: [object Text]