使用缩进序列化动态创建的 HTML



使用 appendChild(( 在 html 文档中创建了一堆元素后,我正在尝试将修改后的页面保存在客户端上。将其发送到服务器似乎有点没有必要,所以我选择了:

var save = document.createElement("a");
save.classList.add("button");
save.textContent = "save";
save.download = "layout-save.html"
save.onclick = function(event) {
var output = [];
// serialize document to output
var file = new window.Blob(output,{type:"text/html"});
save.href = window.URL.createObjectURL(file);
}
document.body.appendChild(save);

但是,新创建的元素当然不会缩进。我一直在看js-beautify,但我也注意到关于解析和序列化的Mozilla页面声称你可以使用treewalker。

有谁知道我该怎么做这样的事情?或者如果做不到这一点,是否有办法在没有子节点的情况下序列化节点以运行这样的递归循环:

var output = [];
var serializer = new XMLSerializer();
function indent(node) {
var ancestor = node;
while (ancestor != document.documentElement) {
output.push("   ");
ancestor = ancestor.parentNode;
}
output.push(/* serialize node tagname + attributes */);
output.push("n");
for (let child of node.children) {
indent(child);
}
output.push(/* node closing tag*/);
}
indent(document.documentElement);

不要犹豫,告诉我如果我吠错了树,谢谢你的时间。

通过回答我自己的问题,您可以序列化浅克隆以获取节点的开始和结束标签:

var save = document.createElement("a");
save.classList.add("button");
save.textContent = "save";
save.download = "layout.html"
save.onclick = function(event) {
document.body.removeChild(save);
var output = [];
var serializer = new XMLSerializer();
function indent(node) {
function offset(node) {
var count = 0;
var ancestor = node;
while (ancestor != document.documentElement) {
count++;
ancestor = ancestor.parentNode;
}
return "t".repeat(count);
}
var buffer = offset(node);
var nodeClone = serializer.serializeToString(node.cloneNode(false)).replace(' xmlns="http://www.w3.org/1999/xhtml"',"");
if (node.children.length) {
let tagSplit = nodeClone.replace(/(<.+>)(</.+>)/,"$1<!--children-->$2").split("<!--children-->");
output.push(buffer + tagSplit[0] + "n");
for (let child of node.children) {
indent(child);
}
output.push(buffer + tagSplit[1] + "n");
} else {
output.push(buffer + nodeClone + "n");
}
}
indent(document.documentElement);
var file = new window.Blob(output,{type:"text/html"});
save.href = window.URL.createObjectURL(file);
}
document.body.appendChild(save);

手动删除 XHTML 命名空间有点可惜,但由于它是 XMLSerializer,我看不到任何解决方法。

最新更新