28

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?

Scruffy
  • 444
  • 1
  • 6
  • 13
  • 2
    Have you considered using the more standard `textContent` instead? – CertainPerformance Aug 19 '19 at 06:44
  • Why don't you try this - ```await page.evaluate(() => document.querySelector("your_selector").innerText)``` Before trying execute in console this ```document.querySelector("your_selector").innerText``` to check whether you're getting the required result. – PySaad Aug 19 '19 at 06:49
  • 1
    @CertainPerformance - You're right that textContent seems to work. However I actually really need the additional features of innerText. But I wonder why it won't work even on my own Interface? – Scruffy Aug 19 '19 at 06:52
  • 1
    @PySaad this throws the same error. – Scruffy Aug 19 '19 at 06:52
  • `innerText` may sometimes be preferable to `textContent` if there are child elements and whitespace in the mix. http://perfectionkills.com/the-poor-misunderstood-innerText/ – simmer Apr 02 '20 at 15:12

3 Answers3

35

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.

Nenad
  • 24,809
  • 11
  • 75
  • 93
6

For those who needs to fix this error for any element returned from querySelector:

const el = document.querySelector<HTMLElement>('#app');

if (el) {
  el.innerText = content;
}
snnsnn
  • 10,486
  • 4
  • 39
  • 44
0

I solved this by using the next syntax:

const title = (document.querySelector(".someselector") as HTMLHeadingElement)?.innerText;

I had to specify the element of the issue. For the question it might be better to use something different than HTMLElement

a0m0rajab
  • 115
  • 7