Finding an Element by an Attribute

Sometimes it is not always possible to uniquely identify an element by using the standard ways such as By.ID or By.Name etc. And there can be any number of reasons why this would be the case. However there is an alternative way to find an element by using one of the element’s attributes:

driver.FindElement(By.CssSelector("[title='Unique Identifier']"));

This example will find the element that has “Unique Identifier” as the value for its title attribute. Using the CSS Selector is an elegant way to find this element, but there are other ways to achieve the same outcome. Using XPath you can achieve the same outcome as per this example:

driver.FindElement(By.XPath("//*[@title='Unique Identifier']"));

However I find that this XPath solution is not as readable as the previous CSS Selector version. There is a plus however to using XPath as we can fine tune the search. The //* part of the XPath indicates that we are to search ALL HTML tags for the specified title. But if you change the //* and replace the asterix with the name of an HTML tag such as img then we can search for only <img> elements that have the specified title.

driver.FindElement(By.XPath("//img[@title='Unique Identifier']"));

If you come across any similar solutions, add them to the comments below.

Leave a Comment