Easiest way, even though I'm not a big fan of the tag -- IFRAME it on a different domain from the rest of the site.
It's client side scripting, if you're exposing anything that could be hacked client-side, there's something fundamentally wrong with how you're coding things... but once you go across domain boundaries you should be safe.
Of course in this age of CSR (client side rendering) a lot of the concepts of accessibility that ALSO provide a security layer are often simply not to be found.
But yeah, run the code in an iframe off a different domain to enable XSS protections. Submit it to the server as content, and have it feed it back assembled.
Which is why the iframe in which your fiddles are shown are typically served from fiddle.jshell.net, instead of jsfiddle.net -- the different domain prevents the child iframe from having access to the parent website's / document's methods. As such all the stuff like window.frameElement.ownerDocument SHOULD be going bits-up face-down preventing anything malicious from occurring.