Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typescript, how to update HTML element's value and text.?

I want to update certain attributes of html element using typescript. Is it possible to do so? Here's my code

HTML:-

<a ref="#" id="userProfileName" style="padding-top: 0px; padding-bottom: 0px; padding-right: 10px; padding-left: 10px;">
<img src="" alt="" id="userProfilePic" class="profile-img" style="width: 56px; height: 50px;"></a>

Typescript:-

document.getElementById('userProfilePic').src = profile.picture;
document.getElementById('userProfileName').textContent = profile.given_name;

Error I'm getting:-

error TS2339: Property 'src' does not exist on type 'HTMLElement'.
like image 448
Raj Bhatia Avatar asked Oct 05 '16 16:10

Raj Bhatia


People also ask

How do you access HTML elements in TypeScript?

To get or access the properties and methods of the div HTML element tag without having errors or red squiggly lines in TypeScript, you have to assert the type for the div HTML element tag using the HTMLElement interface in TypeScript.


1 Answers

The document.getElementById function returns an element of type HTMLElement which does not have the src property.
You need to type assert it to HTMLImageElement:

(document.getElementById('userProfilePic') as HTMLImageElement).src = profile.picture;

The same goes for the HTMLAnchorElement but textContent can be accessed straight from the HTMLElement so no need to cast.

like image 64
Nitzan Tomer Avatar answered Sep 20 '22 17:09

Nitzan Tomer