Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Setting CSS styles with destructured JS object

I am trying to create an object with the styles that I need and then set them to my element simply by destructuring and combining the objects, but for whatever reason it is not working:

const styles = { color: "#FFFFFF" }

const element = document.querySelector(".someElementSelector");

element.style = { ...element.style, ...styles };

However the styles just get set to empty strings, I know that because if I do:

const styles = { color: "#FFFFFF" }

const element = document.querySelector(".someElementSelector");

element.style.color = "#FFFFFF";

element.style = { ...element.style, ...styles };

color is an empty string "", but if I remove the last line with destructuring entirely, the color is being set correctly.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

HTMLElement.style is a read-only object. If you assign a string it automatically instead is assigned to its property cssText.

You can destructure using Object.entries(styles):

const styles = {
  color: "red",
  fontSize: "30px",
  textDecoration: "underline",
  transform: "rotate(45deg)",
  transformOrigin: "top left"
}

for (const [prop, value] of Object.entries(styles)) {
  el.style[prop] = value;
}
<div id="el">ABC</div>

You can also use Object.assign() (which basically is a shortcut to the first example):

const styles = {
  color: "red",
  fontSize: "30px",
  textDecoration: "underline",
  transform: "rotate(45deg)",
  transformOrigin: "top left"
}

Object.assign(el.style, styles);
<div id="el">ABC</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!