I am attempting to put together a function that works in the browser to:
- Take the HTML within an element
- Replace common special characters with HTML entities (i.e. convert
©to©) but not replace characters critical to HTML ( < > / " ' # . etc.) - Download the replaced HTML as a file, or even better yet copy that code to the clipboard
I have been able to get the following to work for points 1 and 3, but the replace function doesn't seem to work on characters within nested HTML elements. I'm not very advanced at javascript and haven't been able to track down a solution for this. Any help is appreciated.
<div id="email-html">
<p>test ©</p>
</div>
<a id="ClickMe" onclick="(function () {
function downloadInnerHtml(filename, elId, mimeType) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
var coHtml = elHtml.replace(/©/g, '©');
mimeType = mimeType || 'text/plain';
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(coHtml));
link.click();
}
var fileName = 'email.html';
downloadInnerHtml(fileName, 'email-html', 'text/html');
})();
" href="#">Click to Download</a>
<script>element to house your script? cramming all of that code into an attribute value looks like a bad idea.<script>element. It's part of a templating engine and I was initially trying to embed it into a specific element (especially during testing) but I can get around that.