Skip to content

Instantly share code, notes, and snippets.

@balbuf
Created May 6, 2016 18:51
Show Gist options
  • Save balbuf/0e11d1cdd2eb88fbcdd8f25b037b80b0 to your computer and use it in GitHub Desktop.
Save balbuf/0e11d1cdd2eb88fbcdd8f25b037b80b0 to your computer and use it in GitHub Desktop.
Sanitize CSS and optionally prepend each selector with another selector to isolate the application of these styles
/**
* Takes a block of CSS and uses the browser's CSS parsing mechanism to sanitize
* the content and return only valid style declarations. Optionally you can
* prepend each selector with another selector to isolate the styles even further.
* A use case would be accepting user-generated CSS.
*/
function sanitizeCSS(css, selectorPrefix) {
var style = document.createElement('style')
, rules
, output = ''
;
style.innerHTML = css;
// need to append the stylesheet to activate the CSSStyleSheet object
document.head.appendChild(style);
// save a reference to the sheet
rules = style.sheet.rules;
// remove the sheet from the document
document.head.removeChild(style);
// loop through all the style blocks and concatenate them
for (var i = 0; i < rules.length; i++) {
if (selectorPrefix) {
output += rules[i].selectorText.split(',').map(function(selector) { return selectorPrefix + ' ' + selector }).join(',');
} else {
output += rules[i].selectorText;
}
output += ' { ' + rules[i].style.cssText + ' }\n';
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment