2017-07-12 12 views
0

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 page on parsing and serializingは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); 

をし、あなたの時間をありがとう。自分の質問への回答の仕方によって

答えて

0

、あなたはノードの開始タグと終了タグを取得するために、浅いクローンをシリアライズすることができます

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なので、私はその周りに何も見えませんでした。

関連する問題