Property ‘innertext’ does not exist on type ‘eventtarget’

The error message “Property ‘innertext’ does not exist on type ‘EventTarget'” typically occurs when attempting to access the `innertext` property on an `EventTarget` object in TypeScript or a similar strongly typed language. The reason for this error is that the `innertext` property does not exist on the `EventTarget` type.

To understand this error better, let’s dive into the details and provide an example to clarify the issue.

Suppose you have an HTML element, such as a `div`, and you are trying to access the `innertext` property of that element when handling an event. Let’s assume the event handler is defined as follows:

function handleClick(event: MouseEvent) {
   const target = event.target;
   console.log(target.innertext);
}

In the above example, we have an event listener function called `handleClick` that takes a `MouseEvent` as a parameter. Inside the function, we retrieve the target of the event using `event.target`. However, when trying to access the `innertext` property on the `target` object, TypeScript throws the aforementioned error.

The correct property to access the text content of an HTML element is called `innerText`, not `innertext`. Therefore, to fix the error, you need to change `.innertext` to `.innerText` in your code, like this:

function handleClick(event: MouseEvent) {
   const target = event.target as HTMLElement;
   console.log(target.innerText);
}

In the modified example, we explicitly typecast the `target` object as `HTMLElement` to ensure TypeScript recognizes it correctly. Then, we use the `innerText` property to access the text content of the target element.

Leave a comment