How to use the OR condition in the seelenium findElements () method for any selector?

I want to get all the WebElement information that has the class name "act" or "dact"

I use the line of code below to get all the class information for "act". Can someone help me use the OR condition in the class name?

List<WebElement> nL2 = driver.findElements(By.className("act"));

Something like that; so I don’t need to write two separate lines for each class.

//this is not working

List<WebElement> nL2 = driver.findElements(By.className("act | dact"));

Thanks!

+6
css-selectors selenium webdriver
source share
2 answers

Can you just combine the two lists?

 List<WebElement> act = driver.findElements(By.className("act")); List<WebElement> dact = driver.findElements(By.className("dact")); List<WebElement> all = new ArrayList<WebElement>(); all.addAll(act); all.addAll(dact); 

Alternatively, you can use the xpath locator suggested by @Alejandro

 List<WebElement> all = driver.findElements(By.xpath("//*[@class='act' or @class='dact']")); 
+7
source share

I know this question is really old, but probably the easiest way to do this is to use a CSS selector like

 driver.findElements(By.cssSelector(".act, .dact")); 

You should prefer CSS selectors for XPath because browser support is better and more efficient (and I think it’s easier to master / understand). CSS selectors can do everything By.className() can plus a lot more. They are very powerful and very useful.

Some links to the CSS selector to get you started.

CSS W3C Selector Link

CSS Sauce Labs Selection Tips

+4
source share

All Articles