Convert CSS Text to JavaScript Object

Convert CSS text to JavaScript object

This is the beginning of a parser that may do what you want. Of course it needs work, especially if you want to handle any generic css that may be provided. This assumes that input css is written as you provided, with the first row being the name of the property, the last row being a '}' and so on.

If you don't want to handle only basic properties, writing a complex parser is not an easy task. For example, what if you declare something like:

input[type="text"],
table > tr:nth-child(2),
#link a:hover {
-webkit-transition: width 2s; /* Safari and Chrome */
}

This is valid css, but how would you extract a valid javascript variable name from it? How to convert -webkit-transition into a meaningful property name? The whole task smells like you're doing it all wrong. Instead of working on a parser, I'd work on a more stable solution at all.

By the way, here is the code you may start from:

    var s = '.mybox {\n';
s += 'display: block;\n';
s += 'width: 20px;\n';
s += 'height: 20px;\n';
s += 'background-color: rgb(204, 204, 204);\n';
s += '}\n';

// split css by line
var css_rows = s.split('\n');

// filter out empty elements and strip ';'
css_rows = css_rows.filter(function(x){ return x != '' }).map(function(x){ return x.trim().replace(';', '') });

// create object
var json_name = css_rows[0].trim().replace(/[\.\{\ \#]/g, '');
eval('var ' + json_name + ' = {};');
// remove first and last element
css_rows = css_rows.splice(1, css_rows.length-2)

for (elem in css_rows)
{
var elem_parts = css_rows[elem].split(':');
var property_name = elem_parts[0].trim().replace('-', '');
var property_value = elem_parts[1].trim();
eval(json_name + '.' + property_name + ' = "' + property_value + '";');
}

Javascript / convert CSS style string into JS object

You could use the Javascript split function: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

First split the string with ; as the separator, and then for each result split with :, placing the items in an object as you go.

e.g.

var result = {},
attributes = input.split(';');

for (var i = 0; i < attributes.length; i++) {
var entry = attributes[i].split(':');
result[entry.splice(0,1)[0]] = entry.join(':');
}

Convert css styles to inline styles with javascript keeping the style units

Couldn't find any way to do this using the built in getComputedStyle(). It also returned too many properties that I wasn't interested in. So I came up with a different approach. Basically to use the same function to loop through an element (and maybe all its children elements) and the use Element.matches() to get all the css rules that apply to the element and apply the properties as they were specified in the stylesheet.

I modified this answer a bit to get the rules from the stylesheet.

Has the added benefit that we can pull either from all the document stylesheets or just from a specific one that is needed for preparing the code to go into our content management systems's rich text editor.

function applyInline(element, recursive = true) {

if (!element) {
throw new Error("No element specified.");
}

const matches = matchRules(element);

// we need to preserve any pre-existing inline styles.
var srcRules = document.createElement(element.tagName).style;
srcRules.cssText = element.style.cssText;

matches.forEach(rule => {
for (var prop of rule.style) {

let val = srcRules.getPropertyValue(prop) || rule.style.getPropertyValue(prop);
let priority = rule.style.getPropertyPriority(prop);

element.style.setProperty(prop,val,priority);
}
});

if (recursive) {
element.children.forEach(child => {
applyInline(child, recursive);
});
}
}

function matchRules(el, sheets) {
sheets = sheets || document.styleSheets;
var ret = [];

for (var i in sheets) {
if (sheets.hasOwnProperty(i)) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (el.matches(rules[r].selectorText)) {
ret.push(rules[r]);
}
}
}
}
return ret;
}

Convert CSS file to string in Javascript/Node.js

You just have to load the contents of the CSS file using NodeJS fs.readFileSync.

const fs = require('fs');

try {
const documentStyles = fs.readFileSync('styles/style.css');
const document = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
${documentStyles}
</style>
</head>
<body>
<p>Here's the test</p>
</body>
</html>
`;
} catch(e) {
console.log('Error:', e.stack);
}

Create a CSSStyleSheet object from a CSS string?

Here's a function that does this:

function CSSString2CSSStyleSheet ( css ) {
const style = document.createElement ( 'style' );
style.innerText = css;
document.head.appendChild ( style );
const {sheet} = style;
document.head.removeChild ( style );
return sheet;
}

How to convert a JSON style object to a CSS string?

A performant answer is to map and join the Object.entries with semicolons:

const style = {
...this.props.style,
background: 'blue',
};

const styleString = (
Object.entries(style).map(([k, v]) => `${k}:${v}`).join(';')
);

It unwraps background:'blue', to background:blue; which works well for CSS


To replace any capital letter with dash lowercase letter

k = k.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);

Convert a CSS string to CSSStyleDeclaration

const styles = "width:20px; height:20px; background:lime;"

const el = document.createElement('div');

el.style.cssText = styles;

const cssStyleDeclaration = el.style;


Related Topics



Leave a reply



Submit