function htmlEncode( html ) { return document.createElement( 'a' ).appendChild( document.createTextNode( html ) ).parentNode.innerHTML; }; function htmlDecode( html ) { var a = document.createElement( 'a' ); a.innerHTML = html; return a.textContent; }; document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value ); //sanity check var html = '<div> & hello</div>'; document.getElementById( 'same' ).textContent = 'html === htmlDecode( htmlEncode( html ) ): ' + ( html === htmlDecode( htmlEncode( html ) ) );
<input id="hidden" type="hidden" value="chalk & cheese" /> <input id="text" value="" /> <div id="same"></div> <script> initializeHeader( 'JavaScript/jQuery HTML Encoding', 'http://stackoverflow.com/q/1219860/918414' ); </script>