1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| <script type="text/javascript"> class VNode { constructor(name, attrs, value, type) { this.name = name this.attrs = attrs this.value = value this.type = type this.children = [] } addChildren(node) { this.children.push(node) } }
function create(node) { let _vnode = null if (node.nodeType === 1) { const attributes = [...node.attributes] const attrs = attributes.reduce((prev, curr) => { prev[curr.name] = curr.value return prev }, {}); _vnode = new VNode(node.nodeName.toLowerCase(), attrs, null, node.nodeType) for (let item of node.childNodes) { _vnode.addChildren(create(item)) } } else if (node.nodeType === 3) { _vnode = new VNode(node.nodeName.toLowerCase(), null, node.nodeValue, node.nodeType) } return _vnode }
let vnode = create(document.querySelector("#root")) console.log(vnode);
function parse(node) { let nodeEl = null if (node.type === 1) { nodeEl = document.createElement(node.name) for (let key in node.attrs) nodeEl.setAttribute(key, node.attrs[key]) node.children.forEach(item => { nodeEl.appendChild(parse(item)) }); } else { nodeEl = document.createTextNode(node.value) } return nodeEl }
let dom = parse(vnode) console.log(dom); </script>
|