A simple getCSSCount for use with Selenium-RC
We know that XPath runs slowly in IE, but XPath has the getXPathCount method. And CSS runs quickly but Selenium doesn’t have a corresponding getCSSCount method.
I looked around for a simple way of getting count from a CSS selector.
I found this blog post by Aditya Ivaturi, but since I like to keep my Selenium setup and tests pretty simple, I wanted a much lower maintenance way of implementing the getCSSCount functionality.
So rather than amending the core in the jar file as Aditya did, or using user-extensions, I took the key JavaScript functionality presented in Aditya’s blog post and ran it with a get_eval.
Thus the following helper method:
private int getCSSCount(String aCSSLocator){
String jsScript = "var cssMatches = eval_css(\"%s\", window.document);cssMatches.length;";
return Integer.parseInt(selenium.getEval(String.format(jsScript, aCSSLocator)));
}
Which you could use:
assertEquals(6, getCSSCount("*"));
assertEquals(1,getCSSCount("p[id='para1']"));
This satisfied the itch I needed to scratch and it seems pretty low maintenance between Selenium versions.



Awesome! Your posts on CSS selectors are very timely for me.
So the C# version is:
private int getCSSCount(String aCSSLocator)
{
String jsScript = “var cssMatches = eval_css(\”" + aCSSLocator + “\”, window.document);cssMatches.length;”;
return int.Parse(browser.GetEval(jsScript));
}
Where I call the following C# to return the number of options in a element named “realm”:
int numOptions = getCSSCount(”select[name=’realm’] option”);
or
int numOptions = getCSSCount(”select[name=’realm’]>option”);
Thanks for converting it into C#, I hope that can help someone else too.