To locate the provided HTML input element using Playwright with C#, we need to craft a reliable locator that can identify the element uniquely and stably — even if minor UI changes occur.
Here's the HTML snippet for reference:
<input id="date_0"
type="text"
name="date_0"
class="form-control icp-datepicker ng-isolate-scope hasDatepicker ng-touched ng-dirty ng-valid-parse ng-empty ng-invalid ng-invalid-required is-invalid"
icp-datepicker=""
autocomplete="off"
data-popup="true"
title="Date Picker"
ng-model="shift.date"
ng-model-options="{updateOn: 'default', debounce: {default:500}}"
ng-class="{'is-invalid': vm.addForm.date_0.$dirty && !vm.addForm.date_0.$valid}"
required=""
aria-invalid="true"
style=""
data-gtm-form-interact-field-id="1">
✅ Best Practice: Use Unique and Stable Attributes
The best locators in Playwright prioritize attributes that are:
- Static (not dynamically generated)
- Unique on the page
- Descriptive of purpose/function
In your case, here are some strong options:
🔹 Option 1: Use id (Most Recommended)
var inputLocator = page.Locator("#date_0");
✅ Pros:
id is unique (if not duplicated elsewhere on the page)
- Fastest and most stable selector
🚫 Cons:
- Only if
id is truly unique and stable
🔹 Option 2: Use data-gtm-form-interact-field-id
var inputLocator = page.Locator("[data-gtm-form-interact-field-id=\"1\"]");
✅ Pros:
- Attribute-based and often used for tracking — can be relatively stable
🚫 Cons:
- Not very semantic, and may change if tracking logic updates
🔹 Option 3: Use Title Attribute
var inputLocator = page.Locator("[title=\"Date Picker\"]");
✅ Pros:
- Human-readable and meaningful
🚫 Cons:
- Titles can change more often than IDs
🔹 Option 4: Combine Multiple Attributes (More Specific)
var inputLocator = page.Locator("input#date_0[title='Date Picker']");
✅ Pros:
- Combines two stable attributes to increase specificity
🚫 Cons:
- Slightly longer syntax, but still fast and reliable
🔹 Option 5: Use name Attribute (If IDs Are Not Unique)
var inputLocator = page.Locator("input[name='date_0']");
✅ Pros:
- Good fallback if ID is not unique
🚫 Cons:
- Shared across multiple elements in some forms
✅ Final Recommendation:
Use the id selector if it's truly unique:
await page.Locator("#date_0").FillAsync("2024-06-10");
If not, and you want something readable and descriptive:
await page.Locator("input#date_0[title='Date Picker']").FillAsync("2024-06-10");
Or:
await page.Locator("[data-gtm-form-interact-field-id='1']").FillAsync("2024-06-10");
🧪 Tip: Validate Locator in Playwright Test
Before finalizing, run this in your test to ensure it targets only one element:
var count = await page.Locator("#date_0").CountAsync();
Console.WriteLine($"Matched elements: {count}");
If count == 1, you're good to go!
Let me know if you'd like to chain this with actions like .Click(), .FillAsync(), or wait for visibility!