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.

4
  • 2
    Duplicate of How to insert HTML entities with createTextNode?. Inserting text (.textContent, .createTextNode) won’t parse HTML (including HTML entities), as opposed to inserting HTML (.innerHTML, .insertAdjacentHTML). Commented Mar 15, 2021 at 13:15
  • To parse HTML entities securely, try testDiv.appendChild(document.createTextNode(new DOMParser().parseFromString('|&nbsp;&nbsp;&nbsp;&nbsp;|', "text/html").documentElement.textContent));. This will parse the HTML in an independent document which cannot execute any scripts. Commented Mar 15, 2021 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. Commented Mar 15, 2021 at 22:14
  • @importhuh The string possibly not being trusted is exactly the reason. element.innerHTML = "&nbsp;" works fine, but element.innerHTML = '<img src="." onerror="alert(1);">' 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 for more context. Commented Mar 16, 2021 at 3:13

2 Answers 2

2

You can use unicode literal for this case.

document.createTextNode("|\u00A0\u00A0\u00A0\u00A0|")
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.