XPath CSS Class Matching

March 26, 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

Previous
Evan Phoenix at Mountain West Ruby Conf
Evan Phoenix at Mountain West Ruby Conf

I just attended (and thoroughly enjoyed) the Mountain West Ruby Conf, where Evan Phoenix gave a powerful ke...

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...

×

Subscribe to our Newsletter

!
Thank you!
Error - something went wrong!