1. Escaping HTML Characters with a Text Node

A string can be treated as plain text first, then read back through an element’s innerHTML.

Code:
let textNode = document.createTextNode('<span>by zhangxinxu</span>');
let div = document.createElement('div');
div.append(textNode);
console.log(div.innerHTML);
Result:
Text node to innerHTML
Text node value <span>by zhangxinxu</span>
div.innerHTML
Console

2. Unescaping HTML Characters with DOMParser

DOMParser asks the browser to parse escaped HTML as a document, then reads the text content back.

Code:
let str = '&lt;span&gt;by zhangxinxu&lt;/span&gt;';
let doc = new DOMParser().parseFromString(str, 'text/html');
console.log(doc.documentElement.textContent);
Result:
DOMParser text/html
Escaped input &lt;span&gt;by zhangxinxu&lt;/span&gt;
documentElement.textContent
Console

3. Unescaping HTML Characters with a Textarea

A textarea also decodes entities when assigned through innerHTML, which makes its child text node useful for old-browser-style decoding.

Code:
let textarea = document.createElement('textarea');
textarea.innerHTML = '&lt;span&gt;by zhangxinxu&lt;/span&gt;';
console.log(textarea.childNodes[0].nodeValue);
Result:
textarea innerHTML
textarea.innerHTML &lt;span&gt;by zhangxinxu&lt;/span&gt;
childNodes[0].nodeValue
Console

4. Browser-Free Fallback with String Replacement

Outside a browser context, the DOM helpers are unavailable, so a direct string replacement fallback is still useful.

Code:
/**
 * Method for escaping HTML tags
 * @param  {String} str The HTML string to escape
 * @return {String}     The escaped string
 */
var funEncodeHTML = function (str) {
    if (typeof str == 'string') {
        return str.replace(/<|&|>/g, function (matches) {
            return ({
                '<': '&lt;',
                '>': '&gt;',
                '&': '&amp;'
            })[matches];
        });
    }

    return '';
};

/**
 * Method for unescaping HTML tags
 * @param  {String} str The string to unescape
 * @return {String}     The unescaped string
 */
var funDecodeHTML = function (str) {
    if (typeof str == 'string') {
        return str.replace(/&lt;|&gt;|&amp;/g, function (matches) {
            return ({
                '&lt;': '<',
                '&gt;': '>',
                '&amp;': '&'
            })[matches];
        });
    }

    return '';
};

let encoded = funEncodeHTML('<span>by zhangxinxu</span>');
console.log(encoded);
console.log(funDecodeHTML(encoded));
Result:
String replace fallback
funEncodeHTML result
funDecodeHTML result
Console