chitrank
chitrank

Reputation: 77

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');
});

Upvotes: 1

Views: 2232

Answers (2)

trincot
trincot

Reputation: 350310

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.

Upvotes: 2

David
David

Reputation: 31

You might need to change your 2nd line of javascript to:

var elHtml = $("#"+elId).html();

So your complete JavaScript will be

function downloadInnerHtml(filename, elId, mimeType) {
  var elHtml = $("#"+elId).html();
  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');
});

Hope this will help.

Upvotes: 3

Related Questions