Core CSS parsing functionality that converts CSS text into a structured, manipulable object model following the W3C CSS Object Model specification.
Converts CSS text into a CSSStyleSheet object with full support for all CSS rule types, nested rules, and complex selectors.
/**
* Parse CSS text into a CSSStyleSheet object
* @param {string} token - CSS text to parse
* @returns {CSSStyleSheet} Parsed stylesheet object with cssRules array
*/
function parse(token);Usage Examples:
const { parse } = require("cssom");
// Basic CSS parsing
const css = parse("body { color: red; }");
console.log(css.cssRules[0].selectorText); // "body"
console.log(css.cssRules[0].style.color); // "red"
// Complex CSS with multiple rule types
const complexCSS = parse(`
/* Style rules */
.container {
width: 100%;
max-width: 1200px;
}
/* Media queries */
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
/* Keyframes */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* Import rules */
@import url("reset.css");
/* Font face */
@font-face {
font-family: "MyFont";
src: url("font.woff2");
}
`);
console.log(complexCSS.cssRules.length); // Multiple rules parsedThe parser provides detailed error information for malformed CSS with line and character position details.
const { parse } = require("cssom");
try {
const css = parse('body { color: red; unclosed');
} catch (error) {
console.log(error.message); // Error message with position
console.log(error.line); // Line number where error occurred
console.log(error.char); // Character position
console.log(error.styleSheet); // Partial stylesheet parsed before error
}The parser supports a comprehensive set of CSS features:
Important limitations to be aware of:
Example of Property Overwriting:
const css = parse(`
div {
background: gray;
background: linear-gradient(to bottom, white 0%, black 100%);
}
`);
// Only the linear-gradient is preserved
console.log(css.cssRules[0].style.background);
// "linear-gradient(to bottom, white 0%, black 100%)"