@@ -387,6 +387,69 @@ It is recommended to use this only after the other locators don't work for your
387387
388388- [testing - library ' s `ByTestId`](https://testing-library.com/docs/queries/bytestid/)
389389
390+ ## nth
391+
392+ ` ` ` ts
393+ function nth(index: number): Locator
394+ ` ` `
395+
396+ This method returns a new locator that matches only a specific index within a multi - element query result . Unlike ` elements()[n] ` , the ` nth ` locator will be retried until the element is present .
397+
398+ ` ` ` html
399+ <div aria-label="one"><input/><input/><input/></div>
400+ <div aria-label="two"><input/></div>
401+ ` ` `
402+
403+ ` ` ` tsx
404+ page.getByRole('textbox').nth(0) // ✅
405+ page.getByRole('textbox').nth(4) // ❌
406+ ` ` `
407+
408+ ::: tip
409+ Before resorting to ` nth ` , you may find it useful to use chained locators to narrow down your search .
410+ Sometimes there is no better way to distinguish than by element position ; although this can lead to flake , it ' s better than nothing.
411+ :::
412+
413+ ` ` ` tsx
414+ page.getByLabel('two').getByRole('input') // ✅ better alternative to page.getByRole('textbox').nth(3)
415+ page.getByLabel('one').getByRole('input') // ❌ too ambiguous
416+ page.getByLabel('one').getByRole('input').nth(1) // ✅ pragmatic compromise
417+ ` ` `
418+
419+ ## first
420+
421+ ` ` ` ts
422+ function first(): Locator
423+ ` ` `
424+
425+ This method returns a new locator that matches only the first index of a multi - element query result .
426+ It is sugar for ` nth(0) ` .
427+
428+ ` ` ` html
429+ <input/> <input/> <input/>
430+ ` ` `
431+
432+ ` ` ` tsx
433+ page.getByRole('textbox').first() // ✅
434+ ` ` `
435+
436+ ## last
437+
438+ ` ` ` ts
439+ function last(): Locator
440+ ` ` `
441+
442+ This method returns a new locator that matches only the last index of a multi - element query result .
443+ It is sugar for ` nth(-1) ` .
444+
445+ ` ` ` html
446+ <input/> <input/> <input/>
447+ ` ` `
448+
449+ ` ` ` tsx
450+ page.getByRole('textbox').last() // ✅
451+ ` ` `
452+
390453## Methods
391454
392455All methods are asynchronous and must be awaited . Since Vitest 3 , tests will fail if a method is not awaited .
0 commit comments