A method to escape HTML tags as HTML entities | Example code

Try the TextArea element’s existing code for escaping literal text to escape HTML tags as HTML entities using JavaScript.

var escape = document.createElement('textarea');
function escapeHTML(html) {
    escape.textContent = html;
    return escape.innerHTML;
}

function unescapeHTML(html) {
    escape.innerHTML = html;
    return escape.textContent;
}

HTML complete code

<!DOCTYPE html>
<html>
<body>

  <div class="half first"><textarea id="input" placeholder='Paste your HTML in here...' spellcheck="false" autofocus></textarea></div>

  <div class="middle">
    <select id="method">
      <option value="escape">escape</option>
      <option value="unescape">unescape</option>
    </select>
  </div>

  <div class="half last"><textarea id="output" placeholder='Output...' spellcheck="false"></textarea></div>
  <script>
   
    // Escape & Unescape HTML:
    (function() {
      var escapeEl = document.createElement('textarea');

      window.escapeHTML = function(html) {
        escapeEl.textContent = html;
        return escapeEl.innerHTML;
      };

      window.unescapeHTML = function(html) {
        escapeEl.innerHTML = html;
        return escapeEl.textContent;
      };
    })();

// getElementById shortcut:
var $ = function(id, scopeEl) {
  return (scopeEl || document).getElementById(id);
};

// Grab the needed elements:
var inputEl = $('input');
var outputEl = $('output');
var methodToggleEl = $('method');

// Handle input:
function inputHandler() {
  outputEl.value = window[methodToggleEl.value + 'HTML'](inputEl.value);
}
inputHandler();
methodToggleEl.onchange = inputEl.oninput = inputHandler;
</script>
</body>
</html>

Source: stackoverflow.com

Output:

A method to escape HTML tags as HTML entities

Do comment if you have any doubts and suggestion on this HTML code.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.