Javascript Form How to - Encode HTML entity for HTML5 with Javascript








Question

We would like to know how to encode HTML entity for HTML5 with Javascript.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w  ww .j  a  v  a2 s .c  om-->
    input = document.getElementById('input');
    output = document.getElementById('output');
    div = document.createElement('div');
    function update() {
        div.textContent = input.value;
        output.value = div.innerHTML;
    }
    function reverse() {
        div.innerHTML = output.value;
        input.value = div.textContent;
    }
    input.oninput = update;
    output.oninput = reverse;
    
    output.onclick = function() {
        this.select();
    }
}
</script>
</head>
<body>
  <textarea id="input" placeholder="Place your HTML here."></textarea>
  <textarea id="output" placeholder="The escaped string HTML will output here."></textarea>
</body>
</html>

The code above is rendered as follows: