Saturday, April 12, 2025

CSS nth-match and nth-element locator in playwright

In Playwright, :nth-match() is a selector engine pseudo-class that allows you to select the nth element among a list of elements that match a certain selector. It's very handy when you want to interact with a specific occurrence of an element without relying on fragile XPath or brittle CSS indexing.

CSS nth-match and nth-element locator in playwright


CSS nth-match technique to locate element in Playwright

 Syntax

await page.locator(':nth-match(<selector>, <index>)').click();

Example -1 :

Sometimes page contains a number of similar elements, and it is hard to select a particular one. For example:

<section> <button>Buy</button> </section>
<article><div> <button>Buy</button> </div></article>
<div><div> <button>Buy</button> </div></div>


In this case, :nth-match(:text("Buy"), 3) will select the third button from the snippet above. Note that index is one-based.

// Click the third "Buy" button
await page.locator(':nth-match(:text("Buy"), 3)').click();


:nth-match() is also useful to wait until a specified number of elements appear, using locator.waitFor().

// Wait until all three buttons are visible
await page.locator(':nth-match(:text("Buy"), 3)').waitFor();


Example -2 :

If you want to Click the 2nd button with text "Delete"

await page.locator(':nth-match(button:has-text("Delete"), 2)').click();
This will click the second button that contains the text "Delete".

Example -3 :

Get the 3rd li in a list

const thirdItem = await page.locator(':nth-match(li, 3)').textContent();
console.log(thirdItem);

This will get the text in 3rd li in a list.

Example -4 :

If you’re chaining or nesting locators:

await page.locator('div.item').locator(':nth-match(span.price, 2)').click();


N-th element locator

You can narrow down query to the n-th match using the nth= locator passing a zero-based index.

 Syntax

// Click first button
await page.locator('button').locator('nth=0').click();

// Click last button
await page.locator('button').locator('nth=-1').click();



No comments:

Post a Comment