Skip to content

Commit d5b7469

Browse files
committed
Support using CSSRuleLists as input
1 parent 83d0270 commit d5b7469

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ Generate HTML documents from just CSS.
55

66
## Usage
77

8+
From a CSS string.
89
```javascript
910
import { cssToHtml } from 'css-to-html';
1011

@@ -13,6 +14,15 @@ const css = 'p { color: purple; }';
1314
const html = cssToHtml(css);
1415
```
1516

17+
Or from a style element:
18+
```javascript
19+
import { cssToHtml } from 'css-to-html';
20+
21+
const css = document.querySelector('style').sheet.cssRules;
22+
23+
const html = cssToHtml(css);
24+
```
25+
1626

1727
## Example
1828

src/Generator.ts

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
11
/**
2-
* Generate an HTML document from a CSS string.
3-
* @param css The style sheet string.
2+
* Generate an HTML document from CSS.
3+
* @param css The style sheet.
44
* @returns An HTML body element containing the generated DOM.
55
*/
6-
export function cssToHtml(css: string): HTMLBodyElement {
6+
export function cssToHtml(css: CSSRuleList | string): HTMLBodyElement {
77
const output = document.createElement('body');
8-
8+
let styleRules: CSSRuleList | undefined;
99
// Parse the CSS string into a CSSOM.
10-
const styleDocument = document.implementation.createHTMLDocument();
11-
const styleElement = document.createElement('style');
12-
styleElement.textContent = css;
13-
styleDocument.body.append(styleElement);
14-
const styleRules = styleElement.sheet?.cssRules;
10+
if (typeof css === 'string') {
11+
const styleDocument = document.implementation.createHTMLDocument();
12+
const styleElement = document.createElement('style');
13+
styleElement.textContent = css;
14+
styleDocument.body.append(styleElement);
15+
styleRules = styleElement.sheet?.cssRules;
16+
} else if (css instanceof CSSRuleList) {
17+
styleRules = css;
18+
}
19+
1520
if (!styleRules) {
1621
return output;
1722
}

0 commit comments

Comments
 (0)