XPath CSS Class Matching

March 25, 2008 Alex Chaffee

I’m writing Selenium tests again, which means a lot of XPath. Here’s a trick I learned thanks to this article on Push Button Paradise.

The problem is, how do you write XPath that matches one class in a multi-class element like

<div class='foo bar'>

? The standard XPath equality operator matches a full string, so

//div[@class='foo']

won’t work. The solution is arcane but I promise it works:

//div[contains(concat(' ',normalize-space(@class),' '),' foo ')]

Note that there must be spaces on either side of the class name ‘foo’.

Since this is quite a mouthful, I’ve extracted it into a helper method. Here it is in Java:

/**
 * Generates a partial xpath expression that matches an element whose 'class' attribute
 * contains the given CSS className. So to match &lt;div class='foo bar'&gt; you would
 * say "//div[" + containingClass("foo") + "]".
 *
 * @param className CSS class name
 * @return XPath fragment
 */
protected static String containingClass(String className) {
  return "contains(concat(' ',normalize-space(@class),' '),' " + className + " ')";
}

About the Author

Biography

More Content by Alex Chaffee
Previous
Entrepreneur Panel: Monetization Strategies for Startups: Great idea, but how will it make money?
Entrepreneur Panel: Monetization Strategies for Startups: Great idea, but how will it make money?

Pivotal Labs, in collaboration with VentureArchetypes (www.venturearchetypes.com), hosted an entrepreneur p...

Next
Why Rails will Reign Supreme, revisited
Why Rails will Reign Supreme, revisited

Following up from my previous post on the same topic, I'd like to clarify a few points that hopefully addre...