Skip to content

Instantly share code, notes, and snippets.

@peacefixation
Last active March 27, 2019 01:40
Show Gist options
  • Select an option

  • Save peacefixation/1650f98e8d497e0a758b5cccce71d37a to your computer and use it in GitHub Desktop.

Select an option

Save peacefixation/1650f98e8d497e0a758b5cccce71d37a to your computer and use it in GitHub Desktop.
Download the contents of a HTML element
var downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', function () {
var contents = document.getElementById('someDiv').innerHTML;
if (contents.length = 0) {
return;
}
var filename = 'some-filename.txt';
if (navigator.msSaveBlob) { // IE
navigator.msSaveBlob(new Blob([contents], { type: 'text/plain;charset=utf-8;' }), filename);
} else {
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
document.body.append(link);
link.click();
document.body.removeChild(link);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment