Search code examples
javascripthtml-encode

Do I need to "clean up" after HTML Escape a Javascript string?


I have a Javascript application where I need to escape characters like "<" and ">" in a string.

This looks like an ideal solution:

How to escape HTML

function escapeHTML(str){
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(str));
    return p.innerHTML;
}

or a short alternative using the Option() constructor

function escapeHTML(str){
    return new Option(str).innerHTML;
}

Q: Does this actually add "p" (and the associated text) to my DOM?

Q: Do I need a "removeChild()" or any other "cleanup" if all I want to save is the escaped string?


Solution

  • A1: No, that would be if the function also called document.body.appendChild(p);

    A2: No, as you can probably guess from A1. After the function returns, its local variables are discarded, the p becomes unreachable, and will eventually be garbage-collected.