Search code examples
javascriptdomplaywright

Check if element class contains string using playwright


I am trying to get the element of day 18, and check if it has disabled on its class.

<div class="react-datepicker__day react-datepicker__day--tue" aria-label="day-16" role="option">16</div>
<div class="react-datepicker__day react-datepicker__day--wed react-datepicker__day--today" aria-label="day-17" role="option">17</div>
<div class="react-datepicker__day react-datepicker__day--thu react-datepicker__day--disabled" aria-label="day-18" role="option">18</div>

this is my code, assume

this.xpath = 'xpath=.//*[contains(@class, "react-datepicker__day") and not (contains(@class, "outside-month")) and ./text()="18"]'
  async isDateAvailable () {
    const dayElt = await this.page.$(this.xpath)
    console.log(dayElt.classList.contains('disabled'))) \\this should return true

I can't seem to make it work. Error says TypeError: Cannot read property 'contains' of undefined. Can you help point what I am doing wrong here?


Solution

  • You have to evaluate it inside the browser. $ will return an ElementHandle which is a wrapper around the browser DOM element, so you have to use e.g. evaluate then on it. Or simply $eval which will lookup the element, pass it into a callback which gets executed inside the browsers JavaScript engine. This means something like that would work:

    // @ts-check
    const playwright = require("playwright");
    
    (async () => {
      const browser = await playwright.chromium.launch();
      const context = await browser.newContext();
      const page = await context.newPage();
      await page.setContent(`
          <div id="a1" class="foo"></div>
        `)
      console.log(
        await page.$eval("#a1", el => el.classList.contains("foo1"))
      )
      await browser.close();
    })();