SharePoint Newbie
SharePoint Newbie

Reputation: 6082

How do I find all elements which have a css class in coded ui?

I need to find all Html controls which have a given css class.

var htmlControl = new HtmlControl(document);
htmlControl.SearchProperties[HtmlControl.PropertyNames.Class] = @class;
var uiTestControlCollection = htmlControl.FindMatchingControls();

Using the class name works when there is just one css class on the control. If I have more than one css classes applied on the element, can I search for the element by specifying just one css class and not all of them?

Thanks

Upvotes: 2

Views: 2803

Answers (1)

Sebastian Carroll
Sebastian Carroll

Reputation: 1406

You can perform a partial match, like so:

htmlControl.SearchProperties.Add(HtmlControl.PropertyNames.Class, @class, PropertyExpressionOperator.Contains);
var uiTestControlCollection = htmlControl.FindMatchingControls();

The main draw back of this is that it is just a simple string compare. To illustrate, imagine you have two controls A and B. A has class "Test" and B has classes "testdiv topnav". Now if you perform a search for "test", both controls A and B will be selected.

To match a class exactly, you can provide a close as match as possible using the above method and write a helper function to:

  1. Loop through the collection
  2. Get the class of each control
  3. Split the class string on the spaces
  4. Loop through this array and test each for an exact match
  5. Keep the elements where a class matches exactly

Note: This is clearly non-optimal - I'm all ears if someone has a better solution.

Cheers, Seb

Upvotes: 2

Related Questions