Raj Bhatia Raj Bhatia - 6 months ago 80
HTML Question

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

I want to update update certain attributes of html element using typescript. Is it possible, if Yes then how..? I'm providing my code.


<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>


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'.


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.