1213
1213

Reputation: 756

Convert a CSS string to CSSStyleDeclaration

Getting a CSS string from a CSSStyleDeclaration is made with el.style.cssText, but how can I convert a string, e.g. width:20px; height:20px; background:lime; to a CSSStyleDeclaration object?

My final goal is to merge two CSS declarations, one coming from el.style the other as a string. I thought it was easier to convert both as CSSStyleDeclaration objects to merge it. Let me know if you have a better solution.

Upvotes: 1

Views: 1508

Answers (1)

Zachiah
Zachiah

Reputation: 2627

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

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

el.style.cssText = styles;

const cssStyleDeclaration = el.style;

Upvotes: 3

Related Questions