How can I count the number of elements that match my CSS selector? How can I count the number of elements that match my CSS selector? selenium selenium

How can I count the number of elements that match my CSS selector?


As far as I am aware you can't do this using CSS selectors, but there is a command in Selenium for counting by XPath. The following command will verify there are two disabled buttons:

verifyXpathCount | //td[contains(@class, 'x-hide-offsets')]//button | 2

In Selenium RC (Java) this would look more like

assertEquals(selenium.getXpathCount("//td[contains(@class, 'x-hide-offsets')]//button"), 2);


This is now also implemented (without any extra Javascript magic needed) in Selenium Webdriver API Since google still links to this question as a top result, even though Selenium RC has been replaced by Webdriver, hopefully this saves someone time.

Example java code:

int locatorElementSize = driver.findElements(By.cssSelector("yourCSSLocator")).size();


With newer versions of Selenium, there is a function GetCSSCount(string locator). Just thought an update to this question would be useful