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

98
Views
Iterating through an array of specific properties using getComputedStyle()

Sorry for the stupid 101 question. I'm not sure why this is not working. I'm trying to iterate through the various margin properties that are returned using getComputedStyle()

Any help would be greatly appreciated thanks in advance - CES

   const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer);

let tmpStylesArray = ["marginTop", "marginLeft", "marginBottom", "marginRight"];
let x = 0;

for (let i = 0; i < tmpStylesArray.length; i++) {

    //This throws undefined error
    // x = constContentContainerStyles.tmpStylesArray[i];

    //This returns 0
    x = constContentContainerStyles.getPropertyValue(tmpStylesArray[i]);
    console.log(tmpStylesArray[i] + " - " + x);
    
    // returns the correct value
    console.log(constContentContainerStyles.marginTop);
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

getPropertyValue expects hyphen-case names ("margin-top", etc., not "marginTop", etc.).

But you can just use the style object directly via brackets notation:

console.log(constContentContainerStyles[tmpStylesArray[i]]);

That supports camelCase ("marginTop") and hyphen-case ("margin-top"):

const constHTMLContentContainer = document.getElementById("target");

const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer);

const tmpStylesArray = [
    "marginTop",
    "margin-top", // Added this to show it works too
    "marginLeft",
    "marginBottom",
    "marginRight"
];

for (const name of tmpStylesArray) {
    const x = constContentContainerStyles[name];
    const note = name.includes("-") ? "Hyphen case works too: " : "";
    console.log(`${note}${name} = ${x}`);
}
#target {
    margin: 10px 20px 30px 40px;
}
<div id="target">x</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!