Menu
Choose a product
Viewing: v1.7.x (latest)
Find another version
Scroll for more
Open source
filter(options)
Returns a new Locator that matches only elements containing or excluding specified text.
| Parameter | Type | Default | Description |
|---|---|---|---|
| options | object | null | If not provided, the method behaves like a no-op and returns a locator identical to the original one. |
| options.hasText | string or RegExp | null | Matches only elements that contain the specified text. String or regular expression. Optional. |
| options.hasNotText | string or RegExp | null | Matches only elements that do not contain the specified text. String or regular expression. Optional. |
Returns
| Type | Description |
|---|---|
| Locator | A new filtered Locator that can be chained with other methods. |
Example
JavaScript
JavaScript
import { browser } from 'k6/browser';
import { check } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
await page.setContent(`
<ul>
<li>
<h3>Product 1</h3>
<button>Add to cart 1</button>
</li>
<li>
<h3>Product 2</h3>
<button>Add to cart 2</button>
</li>
</ul>
`);
// Filter list items that contain "Product 2" text
const product2Item = page
.locator('li')
.filter({ hasText: 'Product 2' })
.first();
const product2Text = await product2Item.textContent();
console.log(product2Text); // Contains "Product 2" and "Add to cart 2"
// Filter list items that do NOT contain "Product 2" using regex
const product1Item = page
.locator('li')
.filter({ hasNotText: /Product 2/ })
.first();
const product1Text = await product1Item.textContent();
console.log(product1Text); // Contains "Product 1" and "Add to cart 1"
await page.close();
}Was this page helpful?
Related resources from Grafana Labs
Additional helpful documentation, links, and articles:
Video

Performance testing and observability in Grafana Cloud
Optimize user experiences with Grafana Cloud. Learn real-time insights, performance testing with k6, and continuous validation with Synthetic Monitoring.
Events

User-centered observability: load testing, real user monitoring, and synthetics
Learn how to use load testing, synthetic monitoring, and real user monitoring (RUM) to understand end users' experience of your apps. Watch on demand.