Reputation: 1135
At the moment, I'm trying the following:
const element = await page.$("#myElement");
const html = element.innerHTML;
I'm expecting the HTML to be printed, but instead I'm getting undefined
.
What am I doing wrong?
Upvotes: 3
Views: 6182
Reputation: 21
You have to use an asynchronous function evaluate.
In my case, I was using puppeteer/jest and all await* solutions was trowing
error TS2531: Object is possibly 'null'
innerHTML with if statement was working for me(part of example) I was searching the member's table for the first unchecked element
while (n) {
let elementI = await page.$('div >' + ':nth-child(' + i + ')' + '> div > div div.v-input__slot > div');
let nameTextI = await page.evaluate(el => el.innerHTML , elementI);
console.log('Mistery' + nameTextI);
{...}
i++;
{...}
}
Upvotes: 0
Reputation: 444
You can use page.$eval
to access innerHTML
pf specified DOM.
Snippet sing page.$eval
const myContent = await page.$eval('#myDiv', (e) => e.innerHTML);
console.log(myContent);
Works great with jest-puppeter
.
Upvotes: 1
Reputation: 28999
You can use page.evaluate()
to get the innerHTML
of an element:
const inner_html = await page.evaluate(() => document.querySelector('#myElement').innerHTML);
console.log(inner_html);
Alternatively, if you must use page.$()
, you can access the innerHTML
using a combination of elementHandle.getProperty()
and elementHandle.jsonValue()
:
const inner_html = await (await (await page.$('#myElement')).getProperty('innerHTML')).jsonValue();
console.log(inner_html);
Upvotes: 7