Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'innerText' does not exist on type 'Element'

I'm using Typescript for Puppeteer. I'm trying to get innerText from an element.

const data = await page.$eval(selector, node => node.innerText);

I'm getting the error:

Property 'innerText' does not exist on type 'Element'

I tried casting to HTMLElement like described in this question: error " Property 'innerText' does not exist on type 'EventTarget' "?

const data = await page.$eval(selector, <HTMLElement>(node: HTMLElement) => node.innerText);

As well as creating my own Interface like this:

interface TextElement extends Element {
    innerText: string;
}

But in each case I'm getting the error that innerText does not exist on this particular type.

Property 'innerText' does not exist on type 'HTMLElement'

Why is this happening and how to deal with this?

like image 959
Scruffy Avatar asked Aug 19 '19 06:08

Scruffy


People also ask

What is innerText property?

The innerText property of the HTMLElement interface represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.

What does innerText mean in JavaScript?

The innerText property of JavaScript is used to get or set the text inside an HTML element and its descendants. The innerText has a similar working phenomenon to innerHTML. Both properties manipulate the content of an HTML element but with different aspects.

Does not exist on type HTMLElement?

The error "Property 'value' does not exist on type 'HTMLElement'" occurs when we try to access the value property on an element that has a type of HTMLElement . To solve the error, use a type assertion to type the element as HTMLInputElement before accessing the property. This is the index.

Does Firefox support innerText?

javascript - 'innerText' works in IE, but not in Firefox - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.


Video Answer


1 Answers

You can fix it like this:

const data = await page.$eval(selector, node => (node as HTMLElement).innerText);

or:

const data = await page.$eval(selector, node => (<HTMLElement>node).innerText);

UPDATE:

So, after some exchange on Github, it's clear why the syntax from this question does not work. It actually defines anonymous generic function.

<HTMLElement>(node: HTMLElement) => node.innerText

Clearer example would be following:

function myFunction<T>(node: T) {
    node.innerText; // Property 'innerText' does not exist on 'T'
}

const data = await page.$eval(selector, myFunction);

Unfortunate naming of T as HTMLElement creates confusion.

like image 145
Nenad Avatar answered Sep 18 '22 14:09

Nenad