Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply style to a TypeScript Node element

I'm currently learning TypeScript but I don't know how to solve this problem properly. I want to style a HTMLElement given as a argument to my styling function like this:

function styleElement(unstyled: HTMLElement) {
  const styled = unstyled.cloneNode(); // styleElement should be a pure function
  styled.style = { opacity: 0 }; // TypeScript says: Property 'style' does not exist on type 'Node'.

  return styled;
}

I have checked the "Node" interface declaration and the style property is missing. As far as I know it is described in the W3C spec, that Node hasn't any style property. But how can I solve my problem with this limitation?

However overwriting the style property on a "HTMLElement" triggers a readonly error, which is strange too.

Thank you!


1 Answers

You can cast:

function styleElement(unstyled: HTMLElement) {
  const styled = unstyled.cloneNode() as HTMLElement;
  styled.style.opacity = 0 // Now works properly.
  // You can't reassign HTMLElement#style, that won't work.

  return styled;
}
like image 98
Madara's Ghost Avatar answered Aug 24 '26 09:08

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!