Error: In Typescript, there is no property named 'src' in the type 'HTMLElement'

I am encountering an issue with Typescript and I'm struggling to find a solution. While the code functions correctly when "compiled," I can't seem to resolve the error that keeps popping up. I have isolated the problematic parts of my code, but I'm unsure about how to address them effectively.

The error message appears in both the Editor and during the Gulp compile:

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

...

element:HTMLElement; /* Defining element */

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

'''

Rendering the element through this method works smoothly—the properties for position, top, and left function without triggering any errors.

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);
};

Answer №1

Since the property src belongs to the HTMLImageElement type and not the HTMLElement type, it's important to declare your variable with the correct subtype if you are certain you'll be dealing with an img element:

element: HTMLImageElement; /* Declaring element */

// ...

this.element = document.createElement('img'); /*creating an img*/

It would also be beneficial to understand that the return type of document.createElement will be the same if you specify "img" as its argument.

Answer №2

By employing casting technique:

(<HTMLImageElement>document.querySelector(".company_logo")).src

Answer №3

const image = document.querySelector('#image');
image.setAttribute('src', 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAGUlEQVR42mP8Xf3iPQHCwsMDAxODAAREkYFyJMAbMhoLCxAIQAADBQsAFMcXi7VAAAAAElFTkSuQmCC');

Changing the image source using the set attribute method.

Answer №4

stick with this:

let imageElement = document.getElementById('imageId') as HTMLImageElement;
imageElement.src = "newSrc";

Answer №5

We have two effective solutions for this issue:

Method 1

To address the problem, insert <HTMLImageElement> before document.getElementById('myId')

var myImg = <HTMLInputElement>document.getElementById('myId');

myImg.src = 'https://picsum.photos/id/237/200/300';

Method 2

Another way to fix the problem is by using setAttribute to assign src to the image element as shown below

var myImg = document.getElementById('myId');

myImg.setAttribute('src', 'https://picsum.photos/id/237/200/300');

Answer №6

Make sure to specify it as HTMLImageElement, which includes a src attribute.

Answer №7

To access the IMG attribute of the target element in React/Typescript, you can first cast the element to HTMLImageElement within the onError event handler:

onError={(e: React.SyntheticEvent<HTMLImageElement, Event>) => (   (e.target as HTMLImageElement).src = DEFAULT_AVATAR ) }

Answer №8

I found success with casting as recommended by @whereDatApp.com. I used a query selector in the following format to achieve my goal:

querySelector("img[name='menubanner']")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrange jQuery UI elements in descending order

I need to rearrange a list in descending order, starting from the highest value down to the lowest. The values are currently listed as 10,9,8,7,6,5,4,3,2,1 and I need to update the data-ids accordingly. jQuery('.photos').sortable({ stop: f ...

Expanding on Slick carousels by using appendDots

I'm encountering an issue with the Slick carousels I have set up. The appendDots parameter is displaying too many navigation dots on each carousel. For example, if there are 3 Slick carousels on a page, each carousel ends up showing 3 sets of dots in ...

React Native Async Storage: displaying a blank page issue

I am facing an issue while attempting to save my data locally using AsyncStorage, specifically with the getData method. const storeData = async (value: string) => { //storing data to local storage of the device try { await AsyncStorage.setItem(& ...

Understanding how to access POST content in Meteor.js is an important aspect

In my Meteor app, I am trying to retrieve data using POST requests. Here is the code snippet I am using on the server side: __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/input', handle: function(req, res, next) { req.on(' ...

An individual referred to as "User" is currently not defined, despite

I am currently working on a react application and I'm facing an issue where the App component does not seem to be receiving my user value even though it is present. Interestingly, the same syntax works perfectly fine in other components. The error me ...

What is the best way to structure files within the css and js folders after running the build command in Vue-cli?

Vue-cli typically generates files in the following structure: - dist -- demo.html -- style.css -- file.commom.js -- file.commom.js.map -- file.umd.js -- file.umd.js.map -- file.umd.min.js -- file.umd.min.js.map However, I prefer to organize them this way: ...

Convert a Material UI dropdown into a Bootstrap dropdown

The reason for this transformation is due to the unsightly appearance of the dropdown from Material UI. Despite that, the code is functioning properly. It features a dropdown with multiple choices, loading a list of strings and their corresponding images. ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

Tips for concealing information within a JSON response using Javascript

I have a JavaScript function that retrieves card information based on its first 6 digits (BIN). const getCardInfo = async (cardNumber, isLive = false) => { const binCode = cardNumber.substring(0, 6); const cachedData = sessionStorage.getItem(`bin_${ ...

The spring submission function requires the use of two parameters

As a beginner in spring web applications, I am facing an issue where the request mapping receives a "dual" parameter when I submit a form. The form structure is as follows: <form action="" method="post" name="myform"> ...... </form> To submit ...

How can we prevent AngularJS from continuously triggering a controller function with every input change?

Here is a simple TODO app created using angularjs. The functionality is working well, but I am facing an issue where angularjs calls the 'remaining' function on every keystroke in the input field!! Can you spot any errors in the code below? < ...

Display a PDF document from a separate domain within an HTML webpage

I am attempting to display a PDF on my website from a different domain. This is the HTML code I am using: <div id="pdfContainer"> <embed id="pdf" type="application/pdf" /> </div> And here is the JavaScript: $.get("http://otherDoma ...

Tips for accessing values from an array in JavaScript

Is there a way to condense the id and name variables into a single variable? I attempted to use $('#vidyagames').tokenInput([variable]); and also tried inputting a URL, but nothing seemed to work. Instead of id and name, I have a function that re ...

Creating a dynamic drag-and-drop layout in React using react-grid-layout

Utilizing the react-grid-layout package for implementing drag-drop and resize components, I have successfully achieved the functionality outlined in the documentation. Description of My Issue My challenge lies in creating a dynamic UI where the layout is ...

Avoiding redundant data in CRUD applications

In a CRUD application (back-end using express and front-end using react-redux), form values are submitted to a mongodb database with the following schema: import mongoose from 'mongoose'; var Schema = mongoose.Schema({ createdAt:{ type: D ...

Can you explain the significance of { 0: T } in this particular type definition?

I stumbled upon this type declaration in my codebase which is meant for non-empty arrays: type NonEmptyArray<T> = T[] & { 0: T } and it functions as expected: const okay: NonEmptyArray<number> = [1, 2]; const alsoOkay: NonEmptyArray<n ...

What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears: import { createStore } from "vuex"; export default ...

TSDX incorporates Rollup under the hood to bundle CSS Modules, even though they are not referenced

I have recently developed a React library with TSDX and you can find it here: https://github.com/deadcoder0904/react-typical This library utilizes CSS Modules and applies styles to the React components. Although the bundle successfully generates a CSS fi ...

What is the correct way to test history.push and history.replace in React applications?

When attempting to test the replace or push functions, I am encountering issues. When using mock, it is not being called at all and results in an empty object representing history. The error message I receive states: "Cannot spy the replace property beca ...

A guide on shading specific faces based on their normal vectors' alignment with the camera's view

https://i.sstatic.net/FG4hp.png I'm currently working on a shader that requires darkening the faces with normals perpendicular to the camera (dot product is 0). How can I calculate this dot product and make sure it works correctly? uniform float tim ...