Back to All Questions
Question 41 of 100
Locators
Beginner
What is the importance of getByAltText locator in Playwright?
The Answer
`getByAltText` finds `<img>`, `<area>`, and `<input type='image'>` elements by their `alt` attribute. It's the semantic way to locate images, especially for accessibility validation.
Deep Dive Explanation
A missing or empty `alt` attribute is a WCAG accessibility failure. Tests using `getByAltText` serve a dual purpose: they verify the element is visible AND implicitly validate that proper alt text is in place. If an image is purely decorative, it should have `alt=''`.
example.spec.ts
// HTML: <img src="/logo.png" alt="CareerRaah Logo" />
await expect(page.getByAltText('CareerRaah Logo')).toBeVisible();
// Click an image link
await page.getByAltText('Home').click();
// Validate alt text exists (accessibility check)
const images = page.locator('img');
const count = await images.count();
for (let i = 0; i < count; i++) {
const alt = await images.nth(i).getAttribute('alt');
expect(alt).not.toBeNull(); // All images must have alt text
}