3

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.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Ashin Ashok
  • 111
  • 1
  • 5
  • 1
    Please show your implementation using innerText that returns tags? Sounds highly improbable. See [mre] – charlietfl Jun 07 '21 at 12:23
  • printContents = document.getElementById("flightData-print-section").innerText; But when I use innerText then the text shows without tags and not aligned at all. – Ashin Ashok Jun 07 '21 at 12:30
  • 3
    Please provide the HTML (no pictures) you want to print and the code so far you tried. – ikhvjs Jun 07 '21 at 12:31
  • Alignment is a different constraint not mentioned in the question and you just contradicted that all approaches return tags – charlietfl Jun 07 '21 at 12:31
  • 2
    [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – charlietfl Jun 07 '21 at 12:33
  • Hi Everyone
    Name  Address  Country
    Ashin  current  living
    printContents = document.getElementById("flightData-print-section").innerHTML;
    – Ashin Ashok Jun 07 '21 at 12:48
  • 2
    When adding additional code [edit] the question where it can be properly formatted. Blobs of unformulated code in comment blocks are hard to read and not necessarily noticeable to someone coming to review the actual question – charlietfl Jun 07 '21 at 12:55
  • 1
    @AshinAshok don't put code in comments. [edit] the post and add the code there. – R. Richards Jun 07 '21 at 13:08

3 Answers3

0

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>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

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.

Akram Rabie
  • 473
  • 5
  • 11
-1

try

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