user629283
user629283

Reputation: 349

naturalWidth - Property 'naturalWidth' does not exist on type 'HTMLElement'

I am trying to access "naturalWidth" in typescript however if I get a compile error or or i get a red line under "naturalWidth". Because $("#contentImg").height()) returns 0 for me in JavaScript and TypeScript I cant manipulate the image. The image varies in size. If I do it in javascript its fine. I have tried;

  document.getElementById('contentImg').naturalWidth;
  $("#contentImg")[0].naturalWidth.

This works in JavaScript but not in TypeScript. Is there a way to get the naturalWidth/Height?

Upvotes: 3

Views: 5122

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164347

The document.getElementById returns an HTMLElement which lacks the naturalWidth property.
What you're looking for is the HTMLImageElement which does have this naturalWidth property:

let image =  document.getElementById('contentImg') as HTMLImageElement;
console.log(image.naturalWidth); // should be valid

Upvotes: 12

Related Questions