Recently, while working on my project FeedAPI ImageGrabber I came across the issue where I had to select HTML elements by a given css class. The HTML element can have a single CSS class:
1 | <div class="foo"></div> |
or multiple CSS classes associated with it.
1 | <div class="foo exp tar"></div> |
Now if you want to select the HTML elements with class “foo”, this div element would be one of them.
As, I do not have much experience with XPath, I started to search for a solution. After a lot of search and discussion on Drupal development mailing lists, I arrived at the following XPath :
1 | //*[@class and contains(concat(' ',normalize-space(@class),' '),' $classname ')] |
The normalize-space function replaces all continuous tabs and whitespaces with a single whitespace character. Then, we concatenate the resulting string with two white-spaces, one in the start and other at the last. At last, we search for
1 | ' ' . $classname . ' ' |
in the final string.
I hope it helps.







