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">
| |
</div>
<script>
testDiv = document.getElementById('Test')
testDiv.appendChild(document.createElement('br'))
testDiv.appendChild(document.createTextNode('| |'))
</script>
</body>
On Chromium, it shows up as:
| |
| |
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.
.textContent,.createTextNode) won’t parse HTML (including HTML entities), as opposed to inserting HTML (.innerHTML,.insertAdjacentHTML).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.element.innerHTML = " "works fine, butelement.innerHTML = '<img src="." onerror="alert(1);">'can be dangerous. Such XSS attacks won’t happen with theDOMParserapproach. 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.