I want to set the text content of an element using JavaScript. If I do this:
var el = document.getElementById('my-element')
el.textContent = '×'
The result is:
<div id="my-element">&times;</div>
I tried using \&
instead but that had no effect. How can I actually insert the entity into the text content?
textContent will not parse the HTML for you.
Use innerHTML instead if you want the specified text to be parsed.
var el = document.getElementById('my-element')
el.textContent = '×'
var el2 = document.getElementById('my-element2')
el2.innerHTML = '×'
<div id="my-element"></div>
<div id="my-element2"></div>
As answered by others, you can't use HTML entities with textContent
,
and there is no need to do so.
Just use the character directly:
el.textContent= "7 × 6 = 42"; // 7 × 6 = 42
el.textContent= "💡 🙂";
Make sure your files are encoded with <meta charset=UTF-8>
. That's a requirement these days anyway.
Some HTML entities are problematic to handle directly, e.g. spaces like  
or
. Here you can use a hexadecimal Unicode escape sequence.
Example: "NO-BREAK SPACE [NBSP]" is codepoint U+00A0.
As Javascript string just write "\xa0"
or "\u00a0"
for that.
// foo bar
el.textContent= "foo\xa0bar";
el.textContent= "foo\u00a0bar";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With