Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an entity with textContent

Tags:

javascript

dom

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">&amp;times;</div>

I tried using \& instead but that had no effect. How can I actually insert the entity into the text content?

like image 949
Scribblemacher Avatar asked Dec 06 '22 12:12

Scribblemacher


2 Answers

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 = '&times;'

var el2 = document.getElementById('my-element2')
el2.innerHTML = '&times;'
<div id="my-element"></div>
<div id="my-element2"></div>
like image 185
Nope Avatar answered Dec 08 '22 02:12

Nope


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 &times; 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 &thinsp; or &nbsp;. 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&nbsp;bar
el.textContent= "foo\xa0bar";
el.textContent= "foo\u00a0bar";
like image 44
j.j. Avatar answered Dec 08 '22 00:12

j.j.