0

I'm trying to add lines to my page using javascript. I'm eventually planning on generating ascii art from it, but that's besides the point. For some reason, the text |    | renders properly as part of html, but not as a textNode. My MRE is as follows:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="Test">
        |&nbsp;&nbsp;&nbsp;&nbsp;|
    </div>
    <script>
        testDiv = document.getElementById('Test')
        testDiv.appendChild(document.createElement('br'))
        testDiv.appendChild(document.createTextNode('|&nbsp;&nbsp;&nbsp;&nbsp;|'))
    </script>
</body>

On Chromium, it shows up as:

|    |
|&nbsp;&nbsp;&nbsp;&nbsp;|

I've tried about 10 different ways to encode the non-breaking space, but I get a similar result no matter what. I've tried using \ and $# for every encoding I can find. I have not tried it on a different browser.

import huh
  • 93
  • 9
  • 2
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+html+entity+not+rendered+createTextNode) of [How to insert HTML entities with createTextNode?](https://stackoverflow.com/q/20941956/4642212). Inserting text (`.textContent`, `.createTextNode`) won’t parse HTML (including HTML entities), as opposed to inserting HTML (`.innerHTML`, `.insertAdjacentHTML`). – Sebastian Simon Mar 15 '21 at 13:15
  • To parse HTML entities securely, try `testDiv.appendChild(document.createTextNode(new DOMParser().parseFromString('|    |', "text/html").documentElement.textContent));`. This will parse the HTML in an independent document which cannot execute any scripts. – Sebastian Simon Mar 15 '21 at 13:22
  • @SebastianSimon can you elaborate on your security comment? Assuming that the string being appended is trusted, I don't see why this is necessary. – import huh Mar 15 '21 at 22:14
  • @importhuh The string possibly not being trusted is exactly the reason. `element.innerHTML = " "` works fine, but `element.innerHTML = ''` can be dangerous. Such XSS attacks won’t happen with the `DOMParser` approach. The code, as written, also ignores HTML elements and only takes the resulting text content of HTML entities. See my answer to [Find and replace specific text characters across a document with JS](https://stackoverflow.com/a/41886794/4642212) for more context. – Sebastian Simon Mar 16 '21 at 03:13

2 Answers2

1

Enclose your text in <pre></pre> tags. It would be rendered as you typed it. You won't need &nbsp;

<pre>
|    |
</pre>
|    |

Javascript Example

<script>
function myFunction() {
  var x = document.createElement("PRE");
  var t = document.createTextNode("|     |");
  x.appendChild(t);
  document.body.appendChild(x);
}
</script>
Pradeep Kumar
  • 6,836
  • 4
  • 21
  • 47
1

You can use unicode literal for this case.

document.createTextNode("|\u00A0\u00A0\u00A0\u00A0|")
Kishieel
  • 1,811
  • 2
  • 10
  • 19