Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
Dev Avatar asked Sep 05 '25 19:09

Dev


1 Answers

This is the same but uses a native PlayWright function for getting attribute values

const inputElement = page.locator('#emailAddress');
const minLength = await inputElement.getAttribute('minLength');
like image 92
Juan Felipe Arellano Avatar answered Sep 08 '25 11:09

Juan Felipe Arellano