Иван Бишевац
Иван Бишевац

Reputation: 14701

Check if element has two classes

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.

Upvotes: 9

Views: 6267

Answers (3)

Dougui
Dougui

Reputation: 7230

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')

Upvotes: 6

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

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
   ]

Upvotes: 2

AJcodez
AJcodez

Reputation: 34236

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

Upvotes: 8

Related Questions