Created
May 6, 2016 18:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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