Filter product cards by text
intermediate Locators Challenge 5 of 22
The catalogue shows product cards, each with an Add to cart button. Write a locator for the Add to cart button of the Mechanical Keyboard card in the main product grid.
Requirements
- Start from the product cards with
page.getByTestId('product-card'). - Narrow to the right card with
.filter({ hasText: ... })(orhas). - Chain to the button inside that card.
- Resolve to exactly one element. The “Recently viewed” sidebar button must not match.
- Do not use
.nth(),.first()or.last().
Expected output
Resolves to exactly 1 element: the "Add to cart" button on the Mechanical Keyboard product card.
Checks (4)
- ○Resolves to exactly the intended element(s)
- ○Scopes to the product cards with getByTestId
- ○Narrows the cards with filter({ hasText }) or filter({ has })
- ○Does not rely on position (nth, first or last)
example.spec.tsLocator engine · not a real Playwright run
Ctrl/⌘ + Enter to check locator · your code is saved in this browser
Results
Check your locator to see which elements it resolves to.
Page under test
matches are outlined in greenView page HTML
<section class="catalog">
<h2>Keyboards and accessories</h2>
<ul class="products">
<li data-testid="product-card">
<h3>Keyboard Wrist Rest</h3>
<p class="price">$19.00</p>
<button type="button">Add to cart</button>
</li>
<li data-testid="product-card">
<h3>Mechanical Keyboard</h3>
<p class="price">$89.00</p>
<button type="button">Add to cart</button>
</li>
<li data-testid="product-card">
<h3>Wireless Mouse</h3>
<p class="price">$35.00</p>
<button type="button">Add to cart</button>
</li>
</ul>
</section>
<aside class="recent">
<h2>Recently viewed</h2>
<ul>
<li class="recent-item">
<a href="/p/kb-101">Mechanical Keyboard</a>
<button type="button">Add to cart</button>
</li>
</ul>
</aside>