What's the use of the CSS selectors containing text options?

So I use xpath locators and slowly convert to CSS.

I haven't found a way to do an exact match based on text.

For example converting //a[text()='Log Out'].

I know you can do css=a:contains('Log Out') but I want to match exactly to the text. Also I know I can do link=Log Out but looking for a solution with CSS.

Answered by Amit Sinha

If you are looking to do Selenium CSS selector contains text, this script might be of some use Trick is to select the parent of the element of one that you are looking for and then search for the child that has the text. public static IWebElement FindByText(this IWebDriver driver, string text)

{
    var list = driver.FindElement(By.CssSelector("#RiskAddressList"));
    var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(":contains('{0}')"); return x;", text), list);
    return ((System.Collections.ObjectModel.ReadOnlyCollection)element)[0];
}

this will return the first element if there is more than one since it's always one element in my case.



Your Answer

Interviews

Parent Categories