0

I'm using google iconfonts in my website.
Normally,the code in HTML is like this:

<i class="material-icons">&#xE87C;</i>

and it will display a 'time' icon on the page: the icon will display

But now I want to add a icon to DOM by using appendChild() method.the code is:

var my_element = document.getElementById("icon-div");

// create a i tag
var i = document.createElement("i");
i.className = "material-icons";
i.textContent = "&#xe192;";

// append the tag to my_element
my_element.appendChild(i);
<html>
  <head>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  </head>

  <body>
    <!--it should be-->
    <i class="material-icons">&#xe192;</i>

    <!--add it by using appendChild method-->
    <div id="icon-div">
    </div>
  </body>
</html>

When I check the <i>(the one in div) in broswer console,its textContent is "&#xe192;",and its innerHTML is "&amp;#xe192;";

So how can I get a icon when I'm add a icon to DOM dynamically.

sputnik
  • 45
  • 4

1 Answers1

2

Use innerHTML instead of textContent:

var my_element = document.getElementById("icon-div");

// create a i tag
var i = document.createElement("i");
i.className = "material-icons";
i.innerHTML = "&#xe192;";

// append the tag to my_element
my_element.appendChild(i);
<html>
  <head>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  </head>

  <body>
    <!--it should be-->
    <i class="material-icons">&#xe192;</i>

    <!--add it by using appendChild method-->
    <div id="icon-div">
    </div>
  </body>
</html>

textContent assumes you're inserting, well, text; so it escapes the input such that it won't be displayed as HTML. You want it to be displayed as HTML.

Regarding performance: textContent is significantly faster than innerHTML, because the browser doesn't need to parse the input, so it's not a bad idea to prefer textContent when possible -- but in this case you actually need that parsing to occur, so it's necessary to take that small performance hit. In most real-world situations the difference is negligible, you'd have to be doing tens of thousands of DOM insertions before the difference would be noticeable.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • thank you very much,Daniel!The solution works!But I still have a question:Is this the only way?Because innerHTML may cost too many memory if I have more icons to add into DOM.(even though,for the same icon,I can use cloneNode() method.) – sputnik May 22 '18 at 13:54
  • That's premature optimization. Unless you're dealing with tens of thousands of innerHTML insertions, that should not be an issue at all. – Daniel Beck May 22 '18 at 14:02
  • No trouble! It's a reasonable question; I added a performance test and a bit of explanation to the answer. – Daniel Beck May 22 '18 at 14:30