Convert the HTML content to a string and print it in a text file

Viewed 145

I am trying to print the HTML content in a .txt file. I tried using innerHTML, innerText and innerContent. But all this are printing with all the tags along with it.

Please refer to the screenshots

Image 1 enter image description here

enter image description here Image 2

Image 1 is how I wanted to show it, but image 2 is how it actually appears.

3 Answers

Each text block seems to be in a <pre>. Create an array from those elements and map the text from each then join with line break(s).

Something like:

const pre = document.querySelectorAll('.content pre')
const txt = [...pre].map(el => el.textContent.trim()).join('\r\n\r\n')

console.log(txt)
<div class="content">
  <pre>Text block 1</pre>
  <pre>Text block 2</pre>
  <pre>Text block 3</pre>
</div>

It is because of when you save an html file in .text format, you actually have a encoded html code (see HTML Entities), and you need to decode it for browser so the browser will not treat it as a string and detects the tags and could render it.

NOTE that Directly convert a text to a render-able html code is s a security bug (XSS), but if you have to, you can use methods like what is showing in this answer.

Or try unescape(str) method.

try

function get_content() {
  var html = document.getElementById("txt").innerHTML;
  document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}
Related