Property 'href' does not exist on type 'HTMLElement' in TS

avatar

Borislav Hadzhiev

Tue Mar 22 20222 min read

banner

Photo by Max Vertsanov

Property 'href' does not exist on type 'HTMLElement' in TS #

The error "Property 'href' does not exist on type 'HTMLElement'" occurs when we try to access the href property on an element that has a type of HTMLElement. To solve the error, use a type assertion to type the element as HTMLAnchorElement before accessing the property.

property href not exist type htmlelement

This is the index.html file for the examples in this article.

index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <a id="example" href="https://example.com">Example</a> <script src="./src/index.ts"></script> </body> </html>

And here is an example of how the error occurs in the index.ts file.

src/index.ts
// 👇️ const link: HTMLElement | null const link = document.getElementById('example'); if (link != null) { // ⛔️ Property 'href' does not exist on type 'HTMLElement'.ts(2339) link.href = 'https://google.com'; }

The reason we got the error is because the return type of the document.getElementById method is HTMLElement | null and the href property doesn't exist on the HTMLElement type.

To solve the error, use a type assertion to type the element as an HTMLAnchorElement.

src/index.ts
const link = document.getElementById('example') as HTMLAnchorElement | null; if (link !== null) { link.href = 'https://google.com'; console.log(link.href); }

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the link variable stores anHTMLAnchorElement or a null value and not to worry about it.

We used a union type to specify that the variable could still be null, because if an HTML element with the provided id does not exist in the DOM, the getElementById() method returns a null value.

We used a simple if statement that serves as a type guard to make sure the link variable doesn't store a null value before accessing its href property.

src/index.ts
const link = document.getElementById('example') as HTMLAnchorElement | null; // 👉️ link has type HTMLAnchorElement or null here if (link != null) { // 👉️ link has type HTMLAnchorElement here link.href = 'https://google.com'; console.log(link.href); }
TypeScript knows that the link variable has a type of HTMLAnchorElement in the if block and allows us to directly access its href property.

It's always a best practice to include null in the type assertion, because the getElementById method would return null if no element with the provided id was found.

Use the search field on my Home Page to filter through my more than 1,000 articles.