Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how to avoid the "escaping" in createTextElement method?

Here is the Jsfiddle demo

document.getElementById("container").appendChild(document.createTextNode(' '))
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div id="container" class="material-icons"></div>
<br>
<div class="material-icons">&#xe145;</div>

I have two <div> node.

&#xe145; is the actual character code for "plus sign" in the font.

However, the one which is appended &#xe145; by Javascript doesn't work.

It seems that &#xe145; is escaped by createTextNode or appendChild...

Does anyone have ideas about how to avoid the escaping..

like image 623
Hanfei Sun Avatar asked Oct 19 '25 05:10

Hanfei Sun


2 Answers

When you create a text node, you're skipping the HTML parse step that would recognize entity notation and produce the corresponding content.

You can use a JavaScript escape sequence however:

document.getElementById("container").appendChild(document.createTextNode('\ue145'))

The string in the JavaScript code is parsed, but it's parsed according to the rules of JavaScript syntax, not HTML syntax.

like image 195
Pointy Avatar answered Oct 21 '25 20:10

Pointy


&#xe145; is an html entity in hex

Try utilizing .innerHTML

var elem = document.getElementById("container");
elem.innerHTML = "&#xe145;";
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div id="container" class="material-icons"></div>
<br>
<div class="material-icons">&#xe145;</div>
like image 22
guest271314 Avatar answered Oct 21 '25 20:10

guest271314