Home > database >  Iterating through an array of specific properties using getComputedStyle()
Iterating through an array of specific properties using getComputedStyle()

Time:10-21

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);
};

CodePudding user response:

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"):

Show code snippet

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related