Edit in JSFiddle

function encodeHTML( html ) {
    return document.createElement( 'div' ).appendChild( document.createTextNode( html ) ).parentNode.innerHTML;
};

console.log( encodeHTML( '<div>hi</div>' ) );