s.dragos s.dragos - 3 months ago 12
Javascript Question

JavaScript:output symbols and special characters

I am trying to include some symbols into a div using JavaScript.

It should look like this:x ∈ ℝ, but all I get is:

x ∈ ℝ
.



var div=document.getElementById("text");
var textnode = document.createTextNode("x ∈ ℝ");
div.appendChild(textnode);

<div id="text"></div>






I had tried
document.getElementById("something").innerHTML="x &#8712; &reals;"
and it worked, so I have no clue why createTextNode method did not.

What should I do in order to output the right thing?

Answer

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".

Comments