When we want to set the path for an image element in html, we use the
src attribute to set it. Using this method in TypeScript without specifying the data type will result in an error “Property ‘src’ does not exist on type ‘Element'”. This article will show you how to fix it by using the correct HTMLImageElement type or using Type Assertions.
The cause of the error “Property ‘src’ does not exist on type ‘Element'”
This error occurs because there is no
src attribute in the Element object. When you have access to this property on the Element object, the error occurs. The object that has this attribute is HTMLImageElement. Let’s see an example of the error below
let image: HTMLElement; image = document.createElement("img"); // Accessing property 'src' which does not exist on Element image.src = "./banner.jpg";
Property 'src' does not exist on type 'HTMLElement'.
In the above example, we create an html element object whose data type is HTMLElement. Then we assign this object the image data type. Since it is an image type, we access the
src attribute to assign a path to the image, but the error occurs because TypeScript is very strict about the data type. If it is an image, it must have a data type is HTMLImageElement.
Solution for the error “Property ‘src’ does not exist on type ‘Element'”
To solve this error, we have to let TypeScript understand that we want to work on an image element by converting the object we are working on to the type HTMLImageElement
Declare correct type
The simplest way is that we edit the code then convert the HTMLElement to HTMLImageElement and in this way we can use the
src attribute to be able to assign the image path to the object.
// Change the HTMLElement to HTMLImageElement let image: HTMLImageElement; image = document.createElement("img"); // Now we can use the 'src' attribute image.src = "./banner.jpg";
Use Type Assertions
If you use the
document.getElementById() statement to get the object in DOM, then this method always returns HTMLElement object, so we will use Type Assertions to let TypeScript understand that it is an image object, and from there, we can use the
src attribute on that object.
// Use Type Assertions to convert to HTMLImageElement let image = document.getElementById("image") as HTMLImageElement; image = document.createElement("img"); // Now we can use the 'src' attribute image.src = "./banner.jpg";
So we have fixed the error “Property ‘src’ does not exist on type ‘Element'”, which occurs because the properties
src does not exist on the Element object. We need to clearly define the data type of the object before working on them. Hopefully, you will fix the error quickly.
Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).