Thursday, August 18, 2011

xpath css class matching

xpath class matching when the element actually has more than one class in the class="foo bar" statement.

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

That's pretty long and is more general than I need. If multi-class entries are normalized already (e.g., no non-space whitespace in there, just spaces), then it's simpler to use just:


//div[contains(@class, "foo")]


That's so much shorter that I generally start with that and only fallback to the longer form if I find any entries in the html that have non-space whitespace.

No comments: