JavaScript:output symbols and special characters

You are including HTML escapes ("entities") in what needs to be text. According to the docs for createTextNode:

data is a string containing the data to be put in the text node

That's it. It's the data to be put in the text node. The DOM spec is just as clear:

Creates a Text node given the specified string.

You want to include Unicode in this string. To include Unicode in a JavaScript string, use Unicode escapes, in the format \uXXXX.

var textnode = document.createTextNode("x \u2208 \u211D");

Or, you could simply include the actual Unicode character and avoid all the trouble:

var textnode = document.createTextNode("x ∈ ℝ");

In this case, just make sure that the JS file is served as UTF-8, you are saving the file as UTF-8, etc.

The reason that setting .innerHTML works with HTML entities is that it sets the content as HTML, meaning it interprets it as HTML, in all regards, including markup, special entities, etc. It may be easier to understand this if you consider the difference between the following:

document.createTextNode("<div>foo</div>");
document.createElement("div").textContent = "<div>foo</div";
document.createElement("div").innerHTML = "<div>foo</div>";

The first creates a text node with the literal characters "<div>foo</div>". The second sets the content of the new element literally to "<div>foo</div>". The third, on the other hand, creates an actual div element inside the new element containing the text "foo".


Every character has a hexadecimal name (for example 0211D). if you want to transform it into a HTML entity, add &#x => &#x0211D; or use the entity name &reals; or the decimal name &#8477; which can be found all here: http://www.w3schools.com/charsets/ref_html_entities_4.asp

But when you use JavaScript, in order to make the browser understand that you want to output a unicode symbol and not a string, escape entities are required. To do that, add \u before the hexadecimal name =>\u211D;.


document.createTextNode will automatically html-escape the needed characters. You have to provide those texts as JavaScript strings, either escaped or not:

document.body.appendChild(document.createTextNode("x ∈ ℝ"));
document.body.appendChild(document.createElement("br"));
document.body.appendChild(document.createTextNode("x \u2208 \u211d"));

EDIT: It's not true that the createTextNode function will do actual html escaping here as it doesn't need to. @deceze gave a very good explanation about the connection between the dom and html: html is a textual representation of the dom, thus you don't need any html-related escaping when directly manipulating the dom.