Skip to content

Instantly share code, notes, and snippets.

@cvan
Created September 18, 2013 04:27
Show Gist options
  • Save cvan/6604544 to your computer and use it in GitHub Desktop.
Save cvan/6604544 to your computer and use it in GitHub Desktop.
sanitizes unescaped HTML to protect you from doing DOM shit like getting XSS'd
function charmin(dirty, whitelist) {
// returns sanitized HTML; accepts two arguments:
// (1) dirty: unescaped HTML
// (2) whitelist: array of allowed HTML tags
var div = document.createElement('div');
document.createDocumentFragment().appendChild(div);
div.innerHTML = dirty;
var naughty = div.querySelectorAll(whitelist && whitelist.length ? ':not(' + whitelist.join('):not(') + ')' : '*');
var i = naughty.length;
while (i--) {
naughty[i].parentNode.removeChild(naughty[i]);
}
return div.innerHTML;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment