Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Feb 2004
    Posts
    17
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Ampersands in innerHTML getting encoded automatically

    I'm having a problem when I want to do something like this in js:

    Code:
    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:

    Code:
    alert(document.getElementById('someElement').innerHTML);
    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 ( & )?

  • #2
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    No way to prevent that unless you use innerText which is an IE-only method. Just replace it with its equivalent value.
    Code:
    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;
    alert(document.getElementById('someElement').innerHTML.htmlDecode());
    I also added &lt; &gt; and &quot;
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #3
    Regular Coder
    Join Date
    Oct 2003
    Posts
    603
    Thanks
    2
    Thanked 1 Time in 1 Post
    Code:
    var someelement = document.getElementById('someElement').innerHTML;
    alert(decodeURI(someelement));


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •