xstax
xstax

Reputation: 106

How can I write text from an HTML snippet to a text file with line breaks?

I have a <div> that receives messages from users in the format of, '[time][username]: message here.

I'm attempting to download the contents of this div to a text file. What I've done works, but, the contents of the download looks like, "<p><i>19:27:05</i> <strong>Bob</strong>: hey</p>". It also displays another div inside it.

How can I ignore these <> tags in the download, and have each individual message appear on a line by itself, similar to how they appear when I render the HTML itself?

Eg:

19:27:05 Bob: hey

19:30:00 Peter: how are you?

script.js:

var downClick = document.getElementById('download');

downClick.addEventListener('click', function(){
    downloadInnerHtml(fileName, 'chat','text/html');
})

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 =  'chat history.txt';

HTML:

<div id="chat" class="chat">
   <div class="istyping" id="istyping"></div>
</div>

Upvotes: 0

Views: 76

Answers (1)

terrymorse
terrymorse

Reputation: 7096

You are seeking the text inside an element, but you are selecting the HTML.

To obtain just the text inside an element and all of its descendants, use HTMLElement.innerText.

From the MDC web docs:

The innerText property of the HTMLElement interface represents the "rendered" text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

Upvotes: 1

Related Questions