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'.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With