Puppeteer: Get innerHTML

Viewed 54991

Does anybody know how to get the innerHTML or text of an element? Or even better; how to click an element with a specific innerHTML? This is how it would work with normal JavaScript:

var found = false
$(selector).each(function() {
    if (found) return;
    else if ($(this).text().replace(/[^0-9]/g, '') === '5' {
        $(this).trigger('click');
        found = true
    }
});

Thanks in advance for any help!

8 Answers

This is how i get innerHTML:

page.$eval(selector, (element) => {
  return element.innerHTML
})

Returning innerHTML of an Element

You can use the following methods to return the innerHTML of an element:

page.$eval()

const inner_html = await page.$eval('#example', element => element.innerHTML);

page.evaluate()

const inner_html = await page.evaluate(() => document.querySelector('#example').innerHTML);

page.$() / elementHandle.getProperty() / jsHandle.jsonValue()

const element = await page.$('#example');
const element_property = await element.getProperty('innerHTML');
const inner_html = await element_property.jsonValue();

Clicking an Element with Specific innerHTML

You can use the following methods to click on an element based on the innerHTML that is contained within the element:

page.$$eval()

await page.$$eval('.example', elements => {
  const element = elements.find(element => element.innerHTML === '<h1>Hello, world!</h1>');
  element.click();
});

page.evaluate()

await page.evaluate(() => {
  const elements = [...document.querySelectorAll('.example')];
  const element = elements.find(element => element.innerHTML === '<h1>Hello, world!</h1>');
  element.click();
});

page.evaluateHandle() / elementHandle.click()

const element = await page.evaluateHandle(() => {
  const elements = [...document.querySelectorAll('.example')];
  const element = elements.find(element => element.innerHTML === '<h1>Hello, world!</h1>');
  return element;
});

await element.click();

You can leverage the page.$$(selector) to get all your target elments and then use page.evaluate() to get the content(innerHTML), then apply your criteria. It should look something like:

const targetEls = await page.$$('yourFancySelector');
for(let target of targetEls){
  const iHtml = await page.evaluate(el => el.innerHTML, target); 
  if (iHtml.replace(/[^0-9]/g, '') === '5') {
    await target.click();
    break;
  }
}

I can never get the .innerHtml to work reliable. I always do the following:

let els = page.$$('selector');
for (let el of els) {
  let content = await (await el.getProperty('textContent')).jsonValue();
}

Then you have your text in the 'content' variable.

You can simply write as below. (no need await sentence in the last part)

const center = await page.$eval('h2.font-34.uppercase > strong', e => e.innerHTML);
<div id="innerHTML">Hello</div>


var myInnerHtml = document.getElementById("innerHTML").innerHTML;
console.log(myInnerHtml);
Related