&nbsp not displaying properly in javascript

860 Views Asked by At

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.

2

There are 2 best solutions below

0
Pradeep Kumar On

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>
0
Kishieel On

You can use unicode literal for this case.

document.createTextNode("|\u00A0\u00A0\u00A0\u00A0|")