Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to set css style generated from getComputedStyles() into a button

Tags:

javascript

css

I want to add all the computed style that will be generated using getComputedStyle() into another button. I have tried with .cssText but it seems something else needs to be done here. any suggestion what can be required to make this happen.

//get styles and storing into sessionstorage

const getStyle = getComputedStyle(document.getElementById("testButton"));
sessionStorage.setItem("getStylesItem", JSON.stringify(getStyle));

//set styles from session object into a button

const jsonValue = JSON.parse(sessionStorage["getStylesItem"]);
const elem = document.getElementById('TestButton1');
elem.style.cssText = jsonValue.cssText;

//dummy json value

{
alignContent: "normal",
alignItems: "center",
alignSelf: "auto",
alignmentBaseline: "auto",
all: "",
animation: "none 0s ease 0s 1 normal none running",
animationDelay: "0s",
animationDirection: "normal",
animationDuration: "0s",
animationFillMode: "none"
}

enter image description here

like image 368
Tammy Avatar asked Feb 20 '26 22:02

Tammy


1 Answers

Loop the CSS object and then form a string. You should use the inline styles for cssText.

const jsonValue = JSON.parse(sessionStorage["getStylesItem"]);
const elem = document.getElementById('TestButton1');

let cssText = '';
for (const property in jsonValue) {
  if (!Number.isNaN(parseInt(property))) continue;
  cssText += `${property}:${jsonValue[property]}`;
}

elem.style.cssText = cssText;

CSSStyleDeclaration object has numeric properties like 0: "align-content", 1: "align-items" so you need to filter non-numeric properties only.

like image 160
polyglot Avatar answered Feb 23 '26 10:02

polyglot



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!