Finding elements that the id increases by 1 C# Selenium

Viewed 55

So I am trying to select an element that has an Id of "edit-". The problem is the element is dynamic. So there could be nothing, 5 different ones, or one. In each case the number following the dash changes based on what edit button I want to select. I am not sure how to "choose" what one I want in a method.

Currently the code I have is

private ReadOnlyCollection<IWebElement> referenceEditButtons => driver.FindElements(By.Id("edit-0"));

public void EditReference(int reference)
    {
        this.referenceEditButtons[reference].Click();
    }

The problem is there technically is only 1 instance of edit-0 on the webpage. I would have to make a variable for each edit button which I want to see if I can stay away from since it would add a bunch of variables and methods. So is there a way to simplify this to make the "referenceEditButtons" variable be able to select any version of "edit-" that I would need it to or something different?

1 Answers

To select each available edit button with the value of id attribute starting with edit- you can use either of the following Locator Strategies:

  • CssSelector:

    private ReadOnlyCollection<IWebElement> referenceEditButtons => driver.FindElements(By.XPath("[id^='edit-']"));
    
  • XPath:

    private ReadOnlyCollection<IWebElement> referenceEditButtons => driver.FindElements(By.XPath("//*[starts-with(@id, 'edit-')]"));
    
Related