Search code examples
rspecwatirwatir-webdriverclass-names

Locating elements without a specific class name


This is in the same vein as this question I asked before - Watir webdriver; counting elements with changing class names. I was able to add the specific number of elements based on using the class name asset-card selectable.

Currently, I am looking to click on more elements to add them to the existing set. Here is my dilemma:

  • When an element is not clicked, the class name is:
    image-card asset-card selectable
  • When an element is clicked, selected is appended to the class name:
    image-card asset-card selectable selected

In my case, I am trying to look for additional elements that only say image-card asset-card selectable and do not include selected. I am not sure how to explicitly locate them.

Is there a regex solution or any other thoughts on how to approach this?


Solution

  • The easiest way to find an element without a certain class is to use a :css locator.

    browser.divs(css: 'div.image-card.asset-card.selectable:not(.selected)')
    

    An explanation of the CSS-selectors:

    • div - This is the tag name of the elements you are trying to match
    • .image-card.asset-card.selectable - This is the list of classes you want the matching elements to have
    • :not(.selected) - This is the list of classes you do not want the matching elements to have

    If you are opposed to CSS-selectors, you could iterate over the elements. Note that this will be slower as it has to make more calls to the browser.

    selectable = browser.divs(class: 'image-card asset-card selectable')
    unselected = selectable.reject { |e| e.class_name.split(' ').include?('selected') }
    

    I have tried to use a Regular Expression before (see my blog post), however it gets pretty messy. I would not recommended going that way.