Open fudx opened 1 year ago
function jsonToDom(json){
// ... todo
if(typeof json === 'string') {
return document.createTextNode(json)
}
const _dom = document.createElement(json.tag)
if(json.attrs) {
for(let [key,value] of Object.entries(json.attrs)) {
_dom.setAttribute(key,value)
}
}
if(json.children && json.children.length) {
json.children.forEach(domJson => {
_dom.appendChild(jsonToDom(domJson))
});
}
return _dom
}
const dom = jsonToDom(json)
app.appendChild(dom)
示例 JSON 输出 假设 HTML 如下:
<div id="container" class="my-container">
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
上面的代码会输出如下 JSON:
{
"tag": "div",
"attributes": {
"id": "container",
"class": "my-container"
},
"children": [
{
"tag": "h1",
"text": "Hello, World!"
},
{
"tag": "p",
"text": "This is a paragraph."
},
{
"tag": "ul",
"children": [
{
"tag": "li",
"text": "Item 1"
},
{
"tag": "li",
"text": "Item 2"
}
]
}
]
}
function domToJson(element) {
const obj = {
tag: element.tagName.toLowerCase()
};
// 获取元素的属性
const attributes = element.attributes;
if (attributes.length > 0) {
obj.attributes = {};
for (let i = 0; i < attributes.length; i++) {
const attr = attributes[i];
obj.attributes[attr.name] = attr.value;
}
}
// 获取元素的文本内容
if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) {
obj.text = element.childNodes[0].textContent.trim();
} else {
// 递归处理子元素
const children = element.children;
if (children.length > 0) {
obj.children = [];
for (let i = 0; i < children.length; i++) {
obj.children.push(domToJson(children[i]));
}
}
}
return obj;
}
// 示例:选择一个 DOM 元素
const element = document.getElementById('container');
// 将 DOM 转换为 JSON
const json = domToJson(element);
console.log(JSON.stringify(json, null, 2));
在html显示为