This is what my html code looks like:
<html>
<style>
body {
font-size: 18px;
}
</style>
<body>
<span id="tiger" style='font-size:100px;'>💡</span>
<button id="btn">SET TIGER</button>
<script>
document.getElementById('btn').addEventListener('click', function (e) {
document.getElementById('tiger').innerText = `🦁`;
});
</script>
</body>
</html>
But it doesn't work and shows just 🦁
instead of emoji when click button. Why is that, how can I set emoji dynamically?
This is what my html code looks like:
<html>
<style>
body {
font-size: 18px;
}
</style>
<body>
<span id="tiger" style='font-size:100px;'>💡</span>
<button id="btn">SET TIGER</button>
<script>
document.getElementById('btn').addEventListener('click', function (e) {
document.getElementById('tiger').innerText = `🦁`;
});
</script>
</body>
</html>
But it doesn't work and shows just 🦁
instead of emoji when click button. Why is that, how can I set emoji dynamically?
-
“Why is that” - because you are not aware of the difference between
innerText
andinnerHTML
…?🦁
only means “numeric HTML character reference” in an HTML context. In a text context, it is just that - text. – C3roe Commented Mar 24, 2020 at 10:46
2 Answers
Reset to default 7HTML Escapes
HTML escapes like "💡" are decoded by the HTML parser when the source document is being parsed.
To set the content of a text node, use a JavaScript string - which technically is encoded in UTF-16.
JavaScript Strings
If you knew the hexadecimal representation of the character in UTF-16 you could set text node content using an escaped string like
element.textContent = "\ud83d\udca1"; // not remended.
If you knew the Unicode value in hex or decimal you could use the static String fromCodePoint
method:
element.textContent = String.fromCodePoint( 0x1f4a1) // or
element.textContent = String.fromCodePoint( 128161 )
Another choice is to escape a 6 hex character code using a unicode escape with curly braces in JavaScript:
element.textContent = '\u{01f4a1}'; // still not remended
However, the method I would remend is to encode the HTML file in UTF-8 when saving and set the text content with a standard string value in code:
element.textContent = '