Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alt attribute encoding with JavaScript

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?

like image 986
Arseni Mourzenko Avatar asked May 05 '10 17:05

Arseni Mourzenko


People also ask

How do you use alt in JavaScript?

Definition and UsageThe alt attribute provides alternative information for an image if a user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).

What character encoding does JavaScript use?

Most JavaScript engines use UTF-16 encoding, so let's detail into UTF-16. UTF-16 (the long name: 16-bit Unicode Transformation Format) is a variable-length encoding: Code points from BMP are encoded using a single code unit of 16-bit. Code points from astral planes are encoded using two code units of 16-bit each.

What is the function of Alt tag?

Definition: An alt tag, also known as "alt attribute" and "alt description," is an HTML attribute applied to image tags to provide a text alternative for search engines. Applying images to alt tags such as product photos can positively impact an ecommerce store's search engine rankings.


1 Answers

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

document.getElementById('formula').alt = 'A \u2192 B';
like image 153
s4y Avatar answered Oct 14 '22 04:10

s4y