I want to get all WebElement information having class name "act" or "dact"
I am using below line of code to get all class information for "act". Can any one help me to use OR condition in class name?
List<WebElement> nL2 = driver.findElements(By.className("act"));
Something similar to this; so that I don't have to write two separate line for each class.
//this is not working
List<WebElement> nL2 = driver.findElements(By.className("act | dact"));
Thanks!
FindElements in Selenium command takes in By object as the parameter and returns a list of web elements. It returns an empty list if there are no elements found using the given locator strategy and locator value. Below is the syntax of find elements command. List<WebElement> elementName = driver.findElements (By.LocatorStrategy ("LocatorValue"));
Find Element command returns the web element that matches the first most element within the web page. Find Elements command returns a list of web elements that match the criteria. Find Element by XPath in Selenium command throws NoSuchElementException if it does not find the element matching the criteria.
CSS Selector is used to provide style rules for web pages and also can be used to identify one or more web elements. Example: Consider the same search box of the Amazon page. It has a class attribute whose value is nav-search-input. Using the same value, the Selenium findElement method can locate the element. 5. Find By XPath
findElement (By by) method finds and returns the first matching element within the current context by the given mechanism. For example if we pass id in above method then it will find and return the first element whose id is a match. If no web element is found with the provided mechanism then it throws NoSuchElementException.
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 could use an xpath locator as suggested by @Alejandro
List<WebElement> all = driver.findElements(By.xpath("//*[@class='act' or @class='dact']"));
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 to XPath because the browser support is better and they are more performant (and I think they are easier to learn/understand). CSS selectors can do everything By.className()
can plus a whole lot more. They are very powerful and very useful.
Some CSS selector references to get you started.
W3C CSS Selector Reference
Sauce Labs CSS Selector Tips
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With