Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
Turn raw CSS into Javascript DOM style Property

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)

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda