Download a file on click using javascript

by Newton Anbarasu

HTML

<div id="main">
    <span>Content of #main div goes here</span>
    <span>Hey!!!!You are getting updated data</span>
</div>

<a href="#" id="downloadLink">Download the inner html of #main</a>

JavaScript

function downloadInnerHtml(filename, elId, mimeType) {
    var elHtml = document.getElementById(elId).innerHTML;
    var link = document.createElement('a');
    mimeType = mimeType || 'text/plain';

    link.setAttribute('download', filename);

    link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
  
    link.click(); 
}

var fileName =  'tags.html'; // You can use the .txt extension if you want

$('#downloadLink').click(function(){
    downloadInnerHtml(fileName, 'main','text/html');
});