Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Unescape HTML in JS

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

Usage

htmlDecode("<img src='myimage.jpg'>"); 
// returns "<img src='myimage.jpg'>"

Comments

  1. mutter
    Permalink to comment#

    Nice. How about the other way around?

  2. kayan
    Permalink to comment#

    This reverses it:

    
      function htmlEncode( input ) {
          return String(input)
              .replace(/&/g, '&')
              .replace(/"/g, '"')
              .replace(/'/g, ''')
              .replace(//g, '>');
    }
    
    • Maybe this is what you mean:

      function htmlEncode( input ) {
          return String(input)
              .replace(/&/g, '&amp;')
              .replace(/"/g, '&quot;')
              .replace(/'/g, ''')
              .replace(/</g, '&lt;')
              .replace(/>/g, '&gt;');
      }
  3. Permalink to comment#

    Nice. How about the other way around?

  4. Permalink to comment#

    But, wouldn’t this execute script tags in the html we are trying to unescape? We wouldn’t want that…

  5. Hayden Schiff
    Permalink to comment#

    This code doesn’t work if you have a tree of nodes to decode instead of just a leaf node. Here’s the solution I used instead:

    function htmlDecode(input) {
        return String(input)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/</g, '');
    }
    

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```