Reputation: 1536
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?
Upvotes: 6
Views: 5097
Reputation: 19376
HTML 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 recommended.
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 recommended
However, the method I would recommend 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 = '💡'
Limited code editor support for Unicode fonts makes this a bit difficult, of course.
Specifying Character Encoding
As mentioned in comment, the character encoding used in HTML files can be specified at the top of the head section before the use of non-ASCII characters. Placing the meta tag
<meta charset="utf-8">
immediately after the opening <html>
tag will achieve this.
While the default encoding in HTML5 is 'utf-8', browsers on older mobile devices may still require use of the meta tag above. See this question from three years ago for more details.
Upvotes: 7
Reputation: 454
<html>
<style>
body {
font-size: 18px;
}
</style>
<body>
<span id="tiger" style='font-size:100px;'>💡</span>
<button id="btn">SET TIGER</button>
<script>
var code = '129409';
//
document.getElementById('btn').addEventListener('click', function (e) {
document.getElementById('tiger').innerText = String.fromCodePoint(parseInt(code));;
});
</script>
</body>
</html>
Kindly check below, Hope your query is resolved.
<html>
<style>
body {
font-size: 18px;
}
</style>
<body>
<span id="tiger" style='font-size:100px;'>💡</span>
<button id="btn">SET TIGER</button>
<script>
var code = '129409';
//
document.getElementById('btn').addEventListener('click', function (e) {
document.getElementById('tiger').innerText = String.fromCodePoint(parseInt(code));;
});
</script>
</body>
</html>
Upvotes: 1