I have a <textarea> that a user types something in, and they are allowed to type html. Once they are done typing, the <textarea> changes back to a <span> that contains what they just typed. However, I want to strip out certain tags such as <script>, <div>, etc… before I put it back into the <span>.
I have a <textarea> that a user types something in, and they are allowed
Share
Believe it or not you can (safely) do this with the browser’s built in HTML parser. Simply create a new div with
document.createElement, toss the contents of the textarea into the div usinginnerHTML, and presto, you’ve got a full blown DOM to work with. And no, scripts contained within this div will not be evaluated.Here’s a simple example that strips from an element all tags that do not appear in an
ALLOWED_TAGSlist.As mentioned, you’ll have to create an empty div container to use this. Here’s one example application of the technique, a function to sanitize strings. Please note, however, that “sanitize” is at this time a misnomer–it will take a lot more work (cleaning attribute strings and such) before this “sanitizer” will output HTML that is truly safe.