Earlier we discussed the Playwright selectOption method to handle the basic <select> dropdown in Playwright. The selectOption method throws an error if the target element is not a <select> element. In this article, let's discuss how to handle dynamic dropdowns or select an option when the select option is not available.
Table of Content
Example 1: Select from Bootstrap Dropdown
Let's select the country India from the bootstrap country dropdown here.

Step 1: Open the Dropdown by clicking on the <button> in <div> containing class bootstrap-select.
await page.locator('button.dropdown-toggle').click()
Step 2: All countries are in <li> inside parent <ul>. Locate the <ul> first.
.locator('ul.dropdown-menu')
Step 3: Locate all the <li>.
.locator('li')
Step 4: Filter for India text using filter method and hasText option and click using click method.
.filter({ hasText:/^India$/}).click()
Code:
test('country dropdown', async ({page}) =>{
await page.goto('http://autopract.com/selenium/dropdown4/')
await page.locator('button.dropdown-toggle').click()
await page
.locator('ul.dropdown-menu')
.locator('li')
.filter({ hasText:/^India$/})
.click();
})
The hasText matches the containing text. For an exact match, use regular expression using a starting and ending forward slash(/) and removing the quotes ('). Also, Use starts with (^) and ends with the ($) symbol.
Example 2: Select from Angular Dropdown
Let's select the color from the dropdown in the header on ngx-admin application. You can also install ngx-admin application on local. Make sure you select any theme to view dropdown.

await page.locator("img[alt='Material Light Theme']").click()
Step 1: Open the Dropdown by clicking on the <button> in <nb-select>
await page.locator('div.header-container>nb-select>button').click()
Step 2: All countries are in <nb-option> inside parent <ul>. Locate the <ul> first.
await page.locator('ul.option-list')
Step 3: Locate all the <nb-option>.
.locator('nb-option')
Step 4: Filter for Corporate text using filter method and hasText option and click using click method.
.filter({ hasText:/^Corporate$/}).click();
Code:
test.only('ngx dropdown', async ({page}) =>{
await page.goto('https://www.akveo.com/ngx-admin')
await page.locator("img[alt='Material Light Theme']").click()
await page.locator('div.header-container>nb-select>button').click()
await page
.locator('ul.option-list')
.locator('nb-option')
.filter({ hasText:/^Corporate$/})
.click();
})
The Corporate option starts with space use (/s) in the regular expression.