javascriptarraysgetcomputedstyle

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

Solution

  • 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>