I'm trying to display a code snippet, which could be in HTML/XML-like languages. To escape HTML entities, I happen to find the following code working:
<!-- html code -->
<pre><code id="foo"></code></pre>
// js code
document.querySelector('#foo').textContent = '<p>a paragraph</p>';
innerText
works as well, but innerHTML
doesn't, which is expected.
I've tested it against latest Chrome and Firefox, but I'm not sure if the auto-escaping of textContent
and innerText
has good support in other major browsers. The relevant DOM and HTML API specs seem a bit vague on this.
So is this behavior required by the spec, thus a safe approach to escape strings?