Property ‘style’ does not exist on type ‘Element’ in TS – How to solve it?

Property ‘style’ does not exist on type ‘Element’ in TS

The error “Property ‘style’ does not exist on type ‘Element'” in TS relates to Typescript and element. What is the reason, and how to solve it? Let’s go into detail now.

The reason for error “Property ‘style’ does not exist on type ‘Element'” in TS

Just look at this example then I will explain why the error occurs.

Example:

<body>
    <h1 class="text">Hello From Learn Share IT</h1>
    <button class="btn">Click here to change h1 color</button>
    <script src="./index.ts"></script>
</body>

index.ts:

const btn = document.querySelector(".btn");
const text = document.querySelector(".text");

btn.addEventListener("click", () => {
    text.style.color = "white";
});

Here I select the button and text with the document.querySelector method. And the value that document.querySelector method returns is Element | null, and of course the type attribute doesn’t exist so it will result in an error

Error:

Property 'style' does not exist on type 'Element'.

Solutions to fix this error

Use ‘as’ keyword

To solve the error “Property ‘style’ does not exist on type ‘element'” in Typescript, you should use the as keyword to set the type of value of querySelector to HTMLElement, which has style property.

index.ts:

const btn = document.querySelector(".btn");
const text = document.querySelector(".text") as HTMLElement | null;

btn.addEventListener("click", () => {
    text.style.fontSize = "50px";
});

Output:

Animated GIF - Find & Share on GIPHY

Here I use the | symbol, which is union type. Because sometimes when there isn’t an element that matches the condition you pass in, the querySelector method will return null. So with union type, your code won’t get an error when it happens. It is like a kind of type guard.

With document.getElementsByClassName method

When you use the document.getElementsByClassName method, the method will return an array of the object of all child elements that match the class name you pass in. So you will have to set the type of collection as HTMLCollectionOf<HTMLElement>.

index.ts:

const btn = document.querySelector(".btn");
const text = document.getElementsByClassName("text") as HTMLCollectionOf<htmlelement>;

btn.addEventListener("click", () => {
    text[0].style.fontSize = "50px";
});</htmlelement>

The value will be an array, so you can access each element by passing in square brackets the element’s index.

Output:

Animated GIF - Find & Share on GIPHY

Summary

In this tutorial, I have explained how to solve the error “Property ‘style’ does not exist on type ‘element'” in TS. You can use the as keyword to set the correct type to use style property. If you have any problems, please comment below. I will answer as possible. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *