chitrank chitrank - 14 days ago 5
CSS Question

How to get formatted text from a div?

I am creating a text editor. Now I am stuck at a point where a user clicks a button and the text is saved to a file (.txt): I am able to get text from the

div
, but not the formatted text (from toolbar of text editor: - bold, italic etc.. via
execommand
)

How to actually do this?

edit



<div id="main">
<span>Content of #main div goes here</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');
});

Answer

Apart from the fact that the .click() call will fail silently in the browsers I have tried with (Firefox, Chrome), the code does send the HTML (not the plain text) to the file.

Here is your code in a more jQuery style, including the change to make the click work:

function downloadInnerHtml(filename, elId, mimeType) {
    var elHtml = $('#' + elId).html();
    mimeType = mimeType || 'text/plain';
    $('<a>').attr('download', filename)
            .attr('href', 'data:' + mimeType+';charset=utf-8,'+ encodeURIComponent(elHtml))
            .get(0)
            .dispatchEvent(new MouseEvent("click"));
}
var fileName =  'tags.html';
$('#downloadLink').click(function(){
    downloadInnerHtml(fileName, 'main','text/html');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
   <span>Content of <b>#main</b> <span style="font-family:Courier New">div</span> goes <font color="red">here</font></span>
</div>
<a href="#" id="downloadLink">Download the inner html of #main</a>

When opening the download page inside a browser, you'll see the formatting (bold, color, font) is applied correctly.