Home > OS >  Typescript - modify style of firstChild of element
Typescript - modify style of firstChild of element

Time:10-25

I have issue with styling firstChild of element in typescript file - here is my code:

let element= document.getElementById("element")
element.children[0].style.height = "80px"

HTML:

<div id="element">
    <div id="element0"></div>
    <div id="element1"></div>
    <div id="element2"></div>
</div>

And the error, which I get in VSC: Property 'style' does not exist on type 'Element'

CodePudding user response:

use css selector instead

let firstChild = document.querySelector("#element :first-child");
firstChild.style.height = "80px";

CodePudding user response:

The Element type does not have a style property. To get access to it, you need to cast to HTMLElement. The way I recommend doing is via generics, like so:

const child = document.querySelector<HTMLElement>("#element :first-child")
child.style = ...

Or by a cast:

const child = document.getElementById("element :first-child") as HTMLElement
child.style = ...
  • Related