Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
Octane Avatar asked Feb 03 '26 11:02

Octane


1 Answers

Looks like you can just write

expect(page.locator('.selector-name')).toHaveClass(/target-class/)

/target-class/ - slashes is required because it's RegExp

For check few classes by one a call I use this helper (It's because api way doesn't work for me https://playwright.dev/docs/test-assertions#locator-assertions-to-have-class):

async function expectHaveClasses(locator: Locator, className: string) {
    // get current classes of element
    const attrClass = await locator.getAttribute('class')
    const elementClasses: string[] = attrClass ? attrClass.split(' ') : []
    const targetClasses: string[] = className.split(' ')
    // Every class should be present in the current class list
    const isValid = targetClasses.every(classItem => elementClasses.includes(classItem))

    expect(isValid).toBeTruthy()
}

In className you can write few classes separated by space:

const result = await expectHaveClasses(page.locator('.item'), 'class-a class-b')
like image 164
Joyful Avatar answered Feb 05 '26 01:02

Joyful