8

I have 2 possible divs.

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

and

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

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

I use Ruby, Capybara and XPath for selecting elements but css is fine if it could solve problem.

Иван Бишевац
  • 13,811
  • 21
  • 66
  • 93

3 Answers3

7

This css selector should work in capybara:

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

which will match

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

AJcodez
  • 31,780
  • 20
  • 84
  • 118
  • 1
    yes but its uglier. http://stackoverflow.com/questions/3881044/how-to-get-html-elements-with-multiple-css-classes – AJcodez Jul 31 '12 at 19:36
5

You can do this :

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

If you don't use rspec, it's this :

page.has_css?('div.a.b')
Dougui
  • 7,142
  • 7
  • 52
  • 87
2

XPath solution:

Use:

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

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

If it is required that the class attribute of any selected div contains exactly (only) these two classes and no other classes, use:

div[contains(concat(' ', @class, ' '), ' a ')
  and
    contains(concat(' ', @class, ' '), ' b ')
  and
    string-length(normalize-space(@class)) = 3
   ]
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431