Reputation: 1417
I have got an HTML page with "export" button. The task is by clicking on the "export HTML" button - copy code of the whole page, remove some elements and then save this code as a separate HTML file. I am using the JavaScript below but it modifies DOM in the browser which shouldn't do.
function exportHTML() {
clean();
var content = document.documentElement.innerHTML;
download(content, "index", "html");
}
function clean() {
var contentToDelete = document.querySelectorAll(".clean");
var editableContent = document.querySelectorAll("[contenteditable=true]");
for (var i = 0; i < editableContent.length; i++) {
editableContent[i].removeAttribute('contenteditable');
}
contentToDelete.forEach((element) => element.remove());
}
function download(content, fileName, fileType) {
var link = document.createElement("a");
var file = new Blob([content], {
type: "html"
});
var downloadFile = fileName + "." + fileType;
link.href = URL.createObjectURL(file);
link.download = downloadFile;
link.click();
}
Can anyone please help?
Upvotes: 0
Views: 115
Reputation: 1417
After a really good advice from @canon I have managed to make it working with the following code:
function exportHTML() {
var strHTML = document.documentElement.innerHTML;
var parser = new DOMParser();
var doc = parser.parseFromString(strHTML, "text/html");
var contentToDelete = doc.querySelectorAll(".clean");
var editableContent = doc.querySelectorAll("[contenteditable=true]");
for (var i = 0; i < editableContent.length; i++) {
editableContent[i].removeAttribute('contenteditable');
}
contentToDelete.forEach((element) => element.remove());
var serializer = new XMLSerializer();
var outHTML = serializer.serializeToString(doc);
var content = outHTML;
download(content, "index", "html");
};
Thanks a lot guys.
Upvotes: 0
Reputation: 35
You're cleaning the code out first, which in your comments, you said you want it to "copy" first. Instead of clean()
first, just copy/store it first and retry.
instead do this:
function exportHTML() {
var content = document.documentElement.innerHTML; // 1st get the original
clean(); // 2nd
download(content, "index", "HTML"); // 3rd
}
It might also be better to store the content outside the function to ensure it's not changed inside the scope of another function.
const content = document.documentElement.innerHTML;
function exportHTML() {
clean(); // 2nd
download(content, "index", "HTML"); // 3rd
}
Upvotes: 1