How to export source content within div to text/html file

前端 未结 4 1422
醉酒成梦
醉酒成梦 2020-12-03 03:44

Let\'s say I have

... Some html ...
and I need to take the html code within this div, place it inside a file and for
4条回答
  •  独厮守ぢ
    2020-12-03 04:28

    You could use something like this:

    Updated jsfiddle with download btn(jquery)

    Initial jsfiddle with plain js and autoexecution

    html

    Hey there

    html - Edit (Added a link to perform this action)

    Download the inner html
    

    Js

    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
    

    JS - Edit

    Since you said in the comments that you are using jQuery i'll call this function from a handler, instead of calling it directly.

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

    You can download as a text, just remove the third argument for function, and it will take the default which is "text/plain", and add the extension .txt to the filename instead of html.

    Note I edited this answer since the person who asked commented that he was looking how to make it work with a handler, he made it work, but just in case. The original code is in the jsfiddle

提交回复
热议问题