Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set multiple CSS style properties in typescript for an element?

Please consider the below snippet. i need to set multiple CSS properties in typescript. for that i have tried the below code.

public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: Object }): void {
        if (attrs !== undefined) {
            Object.keys(attrs).forEach((key: string) => {
                element.style[key] = attrs[key];
            });
        }
    }

for the above code i need to pass the parameters as

let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {font-size:'12px', color : 'red' , margin-top: '5px'});

But the above code throws error(tslint) as Element implicitly has an 'any' type because index expression is not of type 'number'. (property) HTMLElement.style: CSSStyleDeclaration.

Please help me !!!

like image 437
Srinivasan Natarajan Avatar asked Sep 02 '25 05:09

Srinivasan Natarajan


2 Answers

Try using setAttribute. TypeScript does not have the style property on Element.

element.setAttribute("style", "color:red; border: 1px solid blue;");

Some related discussion in this GitHub issue: https://github.com/Microsoft/TypeScript/issues/3263

like image 101
theUtherSide Avatar answered Sep 04 '25 21:09

theUtherSide


The API you were searching for is: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

public static setStyleAttribute(element: HTMLElement, attrs: { [key: string]: string }): void {
    for(const [key, value] of Object.entries(attrs)) {
        element.style.setProperty(key, value);
    }
}

And hyphen is not allowed in object keys, so use ' here, too:

let elem: HTMLElement = document.getElementById('myDiv');
setStyleAttribute(elem, {'font-size':'12px', color: 'red', 'margin-top': '5px'});
like image 41
HolgerJeromin Avatar answered Sep 04 '25 22:09

HolgerJeromin