View Full Version : Ampersands in innerHTML getting encoded automatically

07-31-2006, 06:45 AM
I'm having a problem when I want to do something like this in js:

var someCode = "You & I";
document.getElementById('someElement').innerHTML = someCode;

My problem is with the ampersand. When it is displayed in the browser, it actually looks fine, but it's not what I want/need. It actually sets the innerHTML of the element to "You & I". The ampersand is getting encoded automatically (which I don't want). This would not be much of a concern if all I was doing was setting the innerHTML, but I will also need to access it later on in my script. Later on I will do something like this:


I actually will be doing much more than just the alert, but I'm just demonstrating... Anyway, the problem is that what I originally intended to put inside the "someElement" is not actually what happened. Is there a way that I can prevent the conversion of an ampersand symbol ( & ) to the ampersand entity ( & )?

07-31-2006, 08:05 PM
No way to prevent that unless you use innerText which is an IE-only method. Just replace it with its equivalent value.

String.prototype.htmlDecode = function(){
var str = this;
str = str.replace(/\&lt\;/g, '<').replace(/\&gt\;/g, '>').replace(/\&quot\;/g, '"').replace(/\&amp\;/g, "&");
return str;

var someCode = "You & I"; document.getElementById('someElement').innerHTML = someCode;

I also added &lt; &gt; and &quot;

08-01-2006, 12:00 AM
var someelement = document.getElementById('someElement').innerHTML;