Skip to content

Instantly share code, notes, and snippets.

@mirceapiturca
Created March 11, 2014 17:30
Show Gist options
  • Save mirceapiturca/9490754 to your computer and use it in GitHub Desktop.
Save mirceapiturca/9490754 to your computer and use it in GitHub Desktop.
// Unfortunately there is no native way to 'normalize a selector'
// This little trick makes the browser to do the job instead of implementing your tokenizer and parser
function normalizeSelectors(aSelector) {
var parser = new DOMParser(),
string = '<style>' + aSelector + '{}</style>',
doc = parser.parseFromString(string, "text/html"),
cssRules = doc.querySelector('style').sheet.cssRules;
if (cssRules[0]) {
return cssRules[0].selectorText
} else {
// selector is invalid...
return null
}
}
normalizeSelectors('foo bar') // -> returns 'foo bar'
normalizeSelectors('foo bar: fee') // -> returns null as this is a bad selector
@mirceapiturca
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment