5

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)

1
  • Search for css inliner libraries Commented Aug 16, 2021 at 0:31

2 Answers 2

3

You can try:

  • splitting the string by newlines (\n)

  • looping through each line and checking whether it matches the regex .+{.

    • if it does, we know it's a selector. Extract the selector and store it in a variable
    • otherwise, check whether the line is blank or is a closing curly brace. If it is neither, extract the property and value of the CSS property declaration by splitting by : and trimming the result

const 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);

Sign up to request clarification or add additional context in comments.

1 Comment

Oh this is perfect! Exactly what I was looking for. Using regex is a really smart idea, I don't know why I didn't think of that... Thank you very much for your time and help.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.