Check if an element has two classes

I have 2 possible divs.

<div class='a b'></div> 

and

 <div class='c d'></div> 

Is there any way to check if div element 2 has classes a and b?

I use Ruby, Capybara and XPath to select items, but css is great if it can solve the problem.

+7
source share
3 answers

This css selector should work in capybara:

 page.has_css?('div.a.b') 

which will match

<div class="ab"> but not <div class="a">

+6
source

You can do it:

 page.should have_css('div.a.b') 

If you are not using rspec, this is:

 page.has_css?('div.a.b') 
+5
source

XPath Solution :

Using

 div[contains(concat(' ', @class, ' '), ' a ') and contains(concat(' ', @class, ' '), ' b ') ] 

This selects any child div from the node context whose class attribute contains both the classes "a" and "b" .

If you want the class attribute of any selected div contain exactly (only) these two classes and other classes, use :

 div[contains(concat(' ', @class, ' '), ' a ') and contains(concat(' ', @class, ' '), ' b ') and string-length(normalize-space(@class)) = 3 ] 
+2
source

All Articles