CSS parser for JavaScript?
Here is our open source CSS parser css.js
Here is a simple parsing example :
<script type="text/javascript">
var cssString = ' .someSelector { margin:40px 10px; padding:5px}';
//initialize parser object
var parser = new cssjs();
//parse css string
var parsed = parser.parseCSS(cssString);
console.log(parsed);
</script>
To stringify parsed data structure into CSS string after editing
var newCSSString = parser.getCSSForEditor(parsed);
Main features of our CSS parser is :
- It is lightweight.
- It outputs easy to understand javascript object. No complex AST.
- It is battle tested(and unit tested also) and constantly used in our products(JotForm Form Designer).
- It supports media queries, keyframes and font-face rules.
- It preserves comments while parsing.
Update: I previously mentioned JSCSSP, which is buggy seems to be abandoned. Obviously enough, the css module on NPM is the best:
css = require 'css'
input = '''
body {
font-family: sans-serif;
}
#thing.foo p.bar {
font-weight: bold;
}
'''
obj = css.parse input
sheet = obj.stylesheet
for rule in sheet.rules
rule.selectors = ('#XXX ' + s for s in rule.selectors)
console.log css.stringify(obj)
Output:
#XXX body {
font-family: sans-serif;
}
#XXX #thing.foo p.bar {
font-weight: bold;
}
For what it's worth, JSDOM uses CSSOM.
Also worth mentioning is LESS. While it is primarily a (fantastic) extension to CSS, the LESS parser does give you access to the AST.
A pure CSS stylesheet is also a valid LESS stylesheet, so you can start with what you have now and ease in to LESS' extensions.