views:

425

answers:

2

When I use innerHTML from javascript, the browser (Safari and Firefox at least) seem to replace certain characters and numeric entities with their named entities.

The character \xa0 (non breaking space) gets replaced by  , < (lesser than) gets replaced by <. But for example the umlaut ü is not replaced with ü.

I have not found any documentation for this behaviour.

A simple demo:

<h2 id="withoutnbsp">This does not use en be es pe (uses the \xa0 character)</h2>
<script>alert(document.getElementById("withoutnbsp").innerHTML);</script>

A more elaborate demonstration can be found here:

http://gist.github.com/89434

You can use the "raw" link on the gist page, to view it in your browser.

I need to know exactly which characters innerHTML replaces. Any help is appreciated. Thanks.

+1  A: 

It's probably replacing them with HTML character entities, as per the HTML spec.

Marc Novakowski
Unfortunately it's not that simple. Umlaute and other character, are left alone (ü is NOT converted to ü). I've clarified my question in this regard.
rincewind
+2  A: 

The HTML 5 spec has rules for serializing an HTML fragment when you call innerHTML on it, documented here: Serializing HTML fragments (note that innerHTML isn't in the HTML 4 spec, so the HTML 5 spec is the current reference).

TLDR version of the spec: Spaces, angle brackets, ampersands, equals signs and double quotes are the only chars that get escaped when innerHTML is called.

dfltr