html - In Javascript, how to avoid the "escaping" in createTextElement method? - Stack Overflow

admin2025-04-22  0

Here is the Jsfiddle demo

document.getElementById("container").appendChild(document.createTextNode(' '))
<link href="+Icons" rel="stylesheet">
<div id="container" class="material-icons"></div>
<br>
<div class="material-icons">&#xe145;</div>

Here is the Jsfiddle demo

document.getElementById("container").appendChild(document.createTextNode('&#xe145; '))
<link href="https://fonts.googleapis./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..

Share Improve this question asked Jun 27, 2015 at 15:55 Hanfei SunHanfei Sun 47.2k42 gold badges135 silver badges252 bronze badges 2
  • 1 That's because you are creating a textNode. Create an element and use the innerHTML property. jsfiddle/8a5e7La3/1 – Ram Commented Jun 27, 2015 at 16:01
  • @Vohuman Thanks! But using innerHTML may be quite unsafe.. Is there a way to allow safe characters (no HTML structure) without escaping for &#xe145; – Hanfei Sun Commented Jun 27, 2015 at 16:04
Add a ment  | 

3 Answers 3

Reset to default 9

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.

&#xe145; is an html entity in hex

Try utilizing .innerHTML

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

using innerHTML may be quite unsafe

You can write a RegExp with str.replace to decode html entities in Strings if you want to avoid innerHTML

function decode_html_entities(str) {
    return str.replace(/&(?:#x((?:[0-9a-f]{2}){1,2})|#(\d{1,3})|(amp));/ig, function () {
        if (arguments[1] || arguments[2])
            return String.fromCharCode(arguments[1] ? parseInt(arguments[1], 16) : parseInt(arguments[2], 10));
        var i,
            map = ['&']; // this matches &amp;, add more to the regexp for others
        for (i = 3; i < arguments.length; ++i)
            if (arguments[i]) return map[i-3];
    });
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745297772a295074.html

最新回复(0)