javascriptregextypescriptplaywright

Interact with locator that has dynamic value in playwright


I want to interact with the following locator

<select name="ship[0][596211][address]" id="ship_0_596211_address" class="" title=""></select>

using this line of code:

await page.locator('#ship_0_596211_address').selectOption('24553');

My problem is that 596211 is a dynamic value that for every flow will be different so my line of code with hardcoded value will never work. How do I interact with this specific locator with a dynamic value?

What line of code do I need, also considering that there are other similar locators on the page like:

<select name="ship[1][596211][address]" id="ship_1_596211_address" class="" title=""></select>

Solution

  • If the name attribute is present in all select elements, you can use wildcard selectors in css to match the dynamic value. Something like:

    await page.locator('select[name^="ship[0]["][name$="[address]"]').selectOption('24553');
    

    What it means?

    1. select[name^="ship[0]["][name$="[address]"] - targets all select element whose name attribute starts with ship[0] and ends with [address].

    Below I've created a small sample in html and css which depicts that it targets the expected select and applies styling to it. In playwright, you can use it to locate your element.

    select[name^="ship[0]["][name$="[address]"] {
      /*Try changing above to select[name^="ship[1]["][name$="[address]"]. 
    for applying style to second select. */
      width: 100%;
      max-width: 300px;
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ccc;
      border-radius: 4px;
      appearance: none;
      background-color: #fff;
      margin-bottom: 10px;
    }
    
    select:focus {
      outline: none;
      border-color: #007bff;
      box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
    }
    <select name="ship[0][596211][address]" id="ship_0_596211_address" class="" title="">
      <option value="24551">Address 1</option>
      <option value="24552">Address 2</option>
      <option value="24553">Address 3</option>
    </select>
    
    <select name="ship[1][596211][address]" id="ship_1_596211_address" class="" title="">
      <option value="24551">Address 5</option>
      <option value="24552">Address 6</option>
      <option value="24553">Address 7</option>
    </select>