Search code examples
javascriptplaywright

How to get an element's attribute in a Playwright test?


I'm trying to get an element's attribute in a test. My test looks like this:

test(`Should be at least 5 characters long`, async({ page }) => {
  await page.goto('http://localhost:8080');
  const field = await page.locator('id=emailAddress');

  const _attribute = await field.getAttribute('minlength');
  const minlength = Number(_attribute);

  await expect(minlength).toBeGreaterThanOrEqual(5);    
});

When I run this, I can see that the minlength value is 0. This is because _attribute is null. However, I don't understand why. field is a Locator. But, I can't seem to get the attribute or it's value. What am I doing wrong?


Solution

  • The following worked for me

    const inputElement = page.locator('#emailAddress');
    minLength = await inputElement.evaluate(e => (e as HTMLInputElement).minLength);
    

    EDIT: Use Juan Felipe Arellanos answer instead. I would delete this answer, but I can't delete the accepted answer.