Javascript – Trigger a file download on click of button Javascript with contents from DOM


I want to download a file which is created from DOM element. So a user clicks a button on web page and it invokes a javascript method which may grab the contents of DOM element and prompt user for download.

I am able to grab contents of the DOM element inside a Javascript Var. But not sure how to proceed further.

For grabbing the DOM element i am using:

var elem = document.getElementById("userDownload");

Best Solution

I am not sure if I understand correctly what is the content that you are trying to download. If you have the content (which sounds like the HTML of an element?) stored in a variable, you can try:

("#downloadbutton").click(function() {
  //var content = content of file;
  var dl = document.createElement('a');
  dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
  dl.setAttribute('download', 'filename.txt');;