Reputation: 117
Does somebody have a good method to turn "raw" CSS into DOM style Properties? For example:
Input:
const raw_css = `
h1 {
color: red;
display: block;
}
.myClass {
background: blue;
position: absolute;
opacity: .3;
}
`;
Should be turned into:
Output:
document.querySelector("h1").style.color = "red";
document.querySelector("h1").style.display = "block";
document.querySelector(".myClass").style.background = "blue";
document.querySelector(".myClass").style.position = "absolute";
document.querySelector(".myClass").style.opacity = ".3";
So in some way, it should take the raw CSS from a const/let/var and turn it into multiple rules. For sanity, it would be great if the elements are divided by a new line, like the output example. I've tried to split them by first getting the content between the brackets { ... }
and separating the lines by splitting the ;
... But I don't have any great idea to link the elements to the style rules. I've also searched in Google for similar options, but I didn't seem to find any.
I hope that someone will be able to give me some tips. I know that I didn't provide much and that StackOverflow isn't a code-writing service, but I'm really stuck on this one.
Any help is welcome!
(Edit: I am aware that not every style property can be directly translated into a DOM Style Property. Like: border-top == borderTop. But I could write a simple conditional script that replaces those "non-translatable" properties)
Upvotes: 5
Views: 494
Reputation: 328
CSS in JS supports converting CSS to their JavaScript format with their CLI Tool
Install the JSS CLI tool using:
npm install jss-cli -g
And use it like so:
jss convert source.css
Or you can use npx
to run it once:
npx jss convert source.css
Upvotes: 1
Reputation: 31987
You can try:
splitting the string by newlines (\n
)
looping through each line and checking whether it matches the regex .+{
.
:
and trimming the resultconst selectorRegex = /.+{/gm;
const raw_css = `
h1 {
color: red;
display: block;
}
.myClass {
background: blue;
position: absolute;
opacity: .3;
}
`;
const lines = []
const split = raw_css.split("\n");
var lastSelector;
split.forEach(e => {
const trimmed = e.trim();
if (selectorRegex.test(e)) {
lastSelector = e.replace("{", "").trim()
} else if (trimmed != "}" && trimmed.length > 0) {
const propValue = e.split(":");
const property = propValue[0].trim();
const value = propValue[1].trim();
lines.push(`document.querySelector("${lastSelector}").style.${property} = "${value}"`);
}
})
console.log(lines);
Upvotes: 3