Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to match CSS "<property>: <value>"

I've retrieved a CSS rule from document.styleSheets and am looking now to extract it's properties and values.

cssText = ".expl { position: absolute; background-color: rgb(204, 204, 204); max-width: 150px; }";

Is it possible with regular expressions to retrieve the properties and their appropriate values within a match? Plus, strip the trailing semi-colon.

I want to get the result as follows:

position: absolute // match 1
background-color: rgb(204, 204, 204) // match 2
max-width: 150px // match 3

I've only got to the point where I'm extracting what's within the brackets: (?<={)(.*)(?=}), have no clue with what should I continue.

How do I achieve this?

Thanks in advance!

like image 394
tomsseisums Avatar asked May 20 '26 22:05

tomsseisums


1 Answers

You could just split the string on the ;

document.getElementById(id).style.cssText.split(";")

EDIT:

note that the cssText property of a style object does not contain the selector

enter image description here

EDIT 2:

Ok I did a little more digging and it appears you are getting your cssText property from a CSSStyleRule object. This includes the selectors. You can get a semicolon delimited list of the actual rules with a little more tree traversal. You can get the style object with

document.styleSheets[1].cssRules[0].style.cssText;

instead of

document.styleSheets[1].cssRules[0].cssText;

See this drill down:

enter image description here

like image 122
Joseph Marikle Avatar answered May 22 '26 10:05

Joseph Marikle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!