UNPKG

1.3 kBJavaScriptView Raw
1'use strict';
2/**
3 * dom2js module
4 * @module dom2js
5 * @see module:index
6 */
7const lang = require('zero-lang');
8const sanitize = require('./sanitize');
9
10function filterNodes(nodes) {
11 // FIXME the browser version does not deal with ProcessingInstruction of <?xml version="1.0" encoding="UTF-8"?>
12 nodes = nodes || [];
13 return lang.filter(nodes, (node) => !(node.nodeType === 7 && node.target === 'xml'));
14}
15
16function dom2js(doc) {
17 const obj = {
18 // NOTICE: for HTML, tagName is always UPPERCASE.
19 type: doc.nodeType,
20 };
21
22 // special types
23 if (obj.type === 8 /* doc.COMMENT_NODE */) obj.data = doc.data;
24 if (obj.type === 3 /* doc.TEXT_NODE */) obj.text = sanitize(doc.textContent);
25 if (obj.type === 7 /* doc.PROCESSING_INSTRUCTION_NODE */) {
26 obj.tag = doc.target; // FIXME in browser version, it has tagName
27 obj.data = doc.data;
28 }
29
30 // extra properties
31 if (doc.tagName) obj.tag = doc.tagName;
32 if (doc.childNodes && doc.childNodes.length) {
33 obj.children = lang.map(filterNodes(doc.childNodes), (child) => dom2js(child));
34 }
35 if (doc.attributes) {
36 obj.attributes = {};
37 lang.each(doc.attributes || [], (attr) => {
38 const name = attr.name;
39 obj.attributes[name] = doc.getAttribute(name);
40 });
41 }
42 return obj;
43}
44
45module.exports = dom2js;