Check if element has two classes

2020-07-09 06:34发布

问题:

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.

回答1:

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



回答2:

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


回答3:

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
   ]