Mary
Mary

Reputation: 1135

In Puppeteer, how do I get the innerHTML of a selector?

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

Answers (4)

Dawid Polakowski
Dawid Polakowski

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

Adesh M
Adesh M

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

Wendell Ou
Wendell Ou

Reputation: 127

const html = await page.$eval("#myElement", e => e.innerHTML);

Upvotes: -1

Grant Miller
Grant Miller

Reputation: 28999

page.evaluate():

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

elementHandle.getProperty() / .jsonValue():

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

Related Questions