Question

I would like to be able to match against a class while excluding certain classes as well.

I can use something like follows to get all li elements that match the specified class, but I'm not sure how I can screen out classes at the same time.

b = Watir::Browser.new
free_boxes = b.lis(:class, /cellGridGameStandard/)

I would like to change this into something that will match all li elements with the cellGridGameStandard class, but excludes all elements that also contain either the notEligible class or the ownAlready class.

Was it helpful?

Solution

Here are a couple of options.

Let us assume that the html is like:

<ul>
    <li class="cellGridGameStandard">
        Element 1
    </li>
    <li class="cellGridGameStandard ownAlready">
        Element 2
    </li>
    <li class="cellGridGameStandard notEligible">
        Element 3
    </li>
    <li class="cellGridGameStandard">
        Element 4
    </li>
</ul>

The first and fourth li elements match the specified criteria.

One option would be to check for lis that do not have the ownAlready or notEligible class:

matching = browser.lis(:class => 'cellGridGameStandard')
    .find_all { |li|
        ['ownAlready', 'notEligible'].none? { 
            |class_name| li.class_name.split.include? class_name
        }
    }
p matching.collect(&:text)
#=> ["Element 1", "Element 4"]

Another option, which is easier to write but sometimes considered harder to read, is to use a css locator:

matching = browser.elements(:css => 'li.cellGridGameStandard:not(.ownAlready):not(.notEligible)')
p matching.collect(&:text)
#=> ["Element 1", "Element 4"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top