Fix That Compound Class Error in WebDriver

Fix That Compound Class Error in WebDriver

Multiple class values

HTML allows you to assign multiple values to a class attribute. Though this is handy for applying your style-sheet, it can cause confusion within WebDriver.

So what am I talking about? Consider some HTML that looks like this:

<a class="foregroundRed textBolded" href="http://demo.dennismclaughlin.tech">Next Page</a>

Take a look at the class  attribute. Though we’ve assigned a single string to it, its actually referencing two classes, not one.

If your style-sheet is setup properly, your HTML would render to something like this:

Next Page

One class is to make the “foregroundRed” while the other is to make the “textBolded“.

Use By.CssLocator instead

You can use any other method for finding this  a  tag on your page, but sometimes you can’t and you’re stuck using what you’ve got.

Since you have access to a class , you can use the “By.ClassName” locator.

public static void clickNextPage()
{
     var link = Browser.Driver.FindElement(By.ClassName("foregroundRed textBolded"));
     link.Click();
}

But you’ll quickly see that it results in this error:

OpenQA.Selenium.InvalidSelectorException: ‘invalid selector: Compound class names not permitted

This is a limitation in the way Selenium is interpreting multiple classes at once. A more reliable way to find the a  tag using the classes is to use the “By.CssSelector” locator instead.

Adjust your class names as follows and you’ll be golden:

public static void clickNextPage()
{
     var link = Browser.Driver.FindElement(By.CssSelector(".foregroundRed.textBolded"));
     link.Click();
}

 

 

 

2 Responses

  1. PHenry says:

    I read about this last week from another blog but didn’t quite get it. Your’s makes it quite concise and easy to understand. Thank you. It appears like you’re are replacing the spaces with the dot, is that leading dot necessary\required?

Leave a Reply