<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
</style>
</head>
<body>
<div class="father clearfix" MyAttr>
Iam father
<div class="box1">child1</div>
<div class="box2">child2</div>
<div class="box3">child3</div>
</div>
<button>clickMe</button>
</body>
<script type="text/javascript">
function VNode(tag,text,children,el,attrs){
return {
tag,text,children,el,attrs
}
}
function DomToVnode(dom){
let tag = dom.tagName
let children = []
for(node of dom.childNodes){
if(node.nodeType == 3){
children.push(VNode(undefined,node.data,undefined,node,undefined))
}else{
children.push(DomToVnode(node))
}
}
let attrs = {}
for(let attr of dom.attributes){
attrs[attr.name] = attr.value
}
return VNode(tag,undefined,children,dom,attrs)
}
function VNodeToDom(VNode){
if(VNode.children == undefined){
return document.createTextNode(VNode.text)
}else{
let fragment = document.createElement(VNode.tag)
for(let class_ in VNode.attrs){
fragment.setAttribute(class_,VNode.attrs[class_])
}
console.log(VNode.children)
for(let vnode of VNode.children){
if(vnode.children == undefined){
fragment.appendChild(document.createTextNode(vnode.text))
}else{
fragment.appendChild(VNodeToDom(vnode))
}
}
return fragment
}
}
let father = document.getElementsByClassName('father')[0]
VNODE = DomToVnode(father)
let btn = document.querySelector('button')
btn.addEventListener('click',function(){
let dom = VNodeToDom(VNODE)
console.log('dom,',dom)
document.body.appendChild(dom)
})
</script>
</html>
比较简单的一个实现,具体不做解释了,有问题可以留言。