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

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".