Typescript: property 'src' does not exist in type 'HTMLElement'

I get an error from Typescript and I'm not sure how to fix it. The code works fine when "compiled", but I canโ€™t fix the error. I extracted parts that are related to my code error. I suppose I need to predict src, but don't know how to do it.

Error msg in Editor and Gulp compile:

"Property 'src' does not exist in type 'HTMLElement'.at line 53 col 17"

... element:HTMLElement; /* Defining element */ ''' this.element = document.createElement('img'); /*creating a img*/ ''' 

This is the method that I run to visualize the element, position, top and left all work with an error.

 display() { this.element.src = this.file; /*This is the line that gives the error*/ this.element.style.position = "absolute"; this.element.style.top = this.pointX.toString() + "px"; this.element.style.left = this.pointY.toString() + "px"; document.body.appendChild(this.element); }; 
+7
javascript typescript
source share
5 answers

Because src not a property of type HTMLElement , but HTMLImageElement .

If you are sure you will get the img element, you can declare your variable with the correct subtype:

 element: HTMLImageElement; /* Defining element */ // ... this.element = document.createElement('img'); /*creating a img*/ 

Alternatively, you can see what document.createElement returns. This is the same type if you specify "img" as an argument.

+10
source share

Using casting:

 (<HTMLImageElement>document.querySelector(".company_logo")).src 
+17
source share

You need to declare it as an HTMLImageElement that has an src property.

0
source share
 document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' ); 

Set the source using the set attribute method.

0
source share

Using casting like @ whereDatApp.com suggested working for me. Using the query selector, do the following:

 querySelector("img[name='menubanner']") 
0
source share

All Articles