2

I am using Selenium Protractor and want to select all elements from the following list except one that contains text "Cat" and then perform some operations on the remaining ones.

<div class="mainDiv">
    <div class="childDiv">Dog</div>
    <div class="childDiv">Goat</div>
    <div class="childDiv">Bird</div>
    <div class="childDiv">Cat</div>
    <div class="childDiv">Zebra</div>
</div>

Is there a selector by cssContainingText (or some other) in which I can give a condition to select all elements except the one containing text "Cat"?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
A Hassan
  • 119
  • 10

1 Answers1

1

You can create a List selecting all the elements except one that contains text Cat using the following Locator Strategy:

  • xpath:

    //div[@class='mainDiv']//div[@class='childDiv'][not(contains(.,'Cat'))]
    

When using Selenium and :

The :contains pseudo-class isn't in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver). You can find a detailed discussion in selenium.common.exceptions.InvalidSelectorException with “span:contains('string')”

However, if the elements always appears within the DOM Tree in a specific order, e.g. Cat always at the forth child, you can also use:

  • cssSelector:

    div.mainDiv div.childDiv:not(:nth-child(4))
    

Reference

You can find a couple of relevant discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352