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

Here is the Jsfiddle daemon

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>
      

Run code


I have two <div>

node.

&#xe145;

is the actual character code for the plus sign in the font.

However, the one attached &#xe145;

from Javascript doesn't work.

Seems to be &#xe145;

escaping createTextNode

or appendChild

...

Does anyone have any ideas on how to avoid escaping.

+3


source to share


3 answers


When creating a text node, you will skip the HTML parsing step, which will recognize the entity notation and create the appropriate content.

However, you can use the JavaScript escape sequence:



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

      

A string in JavaScript is parsed, but it is parsed according to the rules of JavaScript syntax, not HTML syntax.

+9


source


&#xe145;

is an html

entity in hexadecimal

Try to use .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>
      

Run code


+2


source


using innerHTML

can be quite insecure

You can write RegExp with str.replace

to decode html objects 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];
    });
}

      

0


source







All Articles