puppeteer howto find element within parent element

Viewed 5620

with cypress I can find child element within element as following:

cy.get('div#Login_form).within(() => {
  cy.get('input[name="human[email]"]').type('John')
  cy.get('input[name="human[password]"]').type('123456')
})

Is there any equivalence in Puppeteer for within()?

Thanks!

2 Answers

Well one thing you can do is to declare your CSS selector paths as follows:

await page.type('div#Login_form > input[name="human[email]"]', 'John');
await page.type('div#Login_form > input[name="human[password]"]', '123456');

Another alternative, which might prove easier to read (even if it does mean more lines of code) would be to do the following:

// Get the form element
const form = await page.$('div#Login_form');

// Get the email and password elements from the form
const email = await form.$('input[name="human[email]"]');
const password = await form.$('input[name="human[password]"]');

// Type the data into each element
await email.type('John');
await password.type('123456');

You can use waitForFunction method with a helper method:

const getChildElement = (handle, selector, options = {}) => {
  const node = handle.querySelector(selector)

  if (!node) return null

  if (options.text && !node.textContent.replace(/\s+/g, ' ').trim().includes(options.text)) {
    return null
  }

  // other checks...

  return node
}

const container = await page.$('#container')
page.waitForFunction(getChildElement, {}, container, '.child', {text: 'Text'})
Related