3

For example, if I am on a product selection page, I would like to select all the elements that aren't sold out.

<div class="item sold-out">Item One - Sold Out</div>
<div class="item">Item Two</div>
<div class="item sold-out">Item Three - Sold Out</div>
<div class="item">Item Four</div>

I would like to write a selector that will only grab items two and four

3 Answers 3

5

You can use the "not" pseudo-class in a CSS selector like this:

div.item:not(.sold-out)
1

Use xpath.

I don't know what language you're using, but in Python it would be:

driver.find_elements_by_xpath('//div[@class="item"]')
8
  • 1
    I'm using C#, and the findelements(by.classname("item") would return all of the items with that class name (a subset of which also have the sold out class).
    – GKS1
    Dec 15, 2014 at 18:54
  • I'm skeptical of that, but if it's true then just use xpath. Dec 15, 2014 at 18:54
  • GKS1 is absolutely right, you have multiple classes separated by spaces. Identifying an element by a class name will find all elements that match, even if they also have additional classes.
    – Sam Woods
    Dec 15, 2014 at 21:26
  • @SamWoods that must be a C# thing, then. Python would treat these differently, which is why I answered the way I did and specified the language I use. Dec 15, 2014 at 21:32
  • This is language agnostic. This is how a browser treats a CSS selector, it always works the same way, regardless of which language you are using for Selenium.
    – Sam Woods
    Dec 15, 2014 at 21:39
-1

List = findElements(By.cssSelector("item:not(.sold-out)")

1
  • 2
    Welcome, Mahesh. Your answer is effectively identical to the accepted answer, but without any explanation. Please edit this answer to explain what your answer adds to the accepted answer for this question.
    – Kate Paulk
    Feb 13, 2017 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.