Alt attribute encoding with JavaScript

Arseni Mourzenko picture Arseni Mourzenko · May 5, 2010 · Viewed 7.1k times · Source

Html entities must be encoded in alt attribute of an image in HTML page. So

<img id="formula" alt="A &rarr; B" src="formula.png" />

will work well.

On the other hand, the same JavaScript code will not work

document.getElementById('formula').alt = 'A &rarr; B';

and will produce A &rarr; B instead of A → B.

How to do it through JavaScript, when it is not possible to put the special (unencoded) characters in the source code?

Answer

s4y picture s4y · May 5, 2010

JavaScript has its own system for escaping special characters in strings:

document.getElementById('formula').alt = 'A \u2192 B';