Home > database >  html selector using predicate of predicate
html selector using predicate of predicate

Time:04-10

enter image description here

I'm working with puppeteer , I want to select a tr by looking for a td with a specific title name.

I tried:

const targetPage = page;
const td = 'td[title="18to22"]';  
const td1 = await waitForSelectors([[td]], targetPage, timeout);

async function waitForSelectors(selectors, frame, timeout) {
  for (const selector of selectors) {
    try {
      return await waitForSelector(selector, frame, timeout);
    } catch (err) {
      console.error(err);
    }
  }
  throw new Error(
    "Could not find element for selectors: "   JSON.stringify(selectors)
  );
}

which works. Now I want to get the parent row (tr)

How do I do this?

CodePudding user response:

You cannot solve it purely with CSS selectors (:has() "has" a poor support so far).
I'd use page.$eval togethet with Node.parentElement (I also recommend optional chaining, but of course a <td> usually has a <tr> parent)

In the below example I retreive its innerText, of course you can use the node element as you need it.

const parent = await page.$eval('td[title="18to22"]', el => el?.parentElement?.innerText)
  • Related