Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find div element by multiple class names?

<div class="value test" /> I'd like to identify that web element. It only has this two classes defined. I cannot do the following as className does not take a space separated value. What are alternatives?

@FindBy(className = "value test") @CacheLookup private WebElement test; 
like image 694
membersound Avatar asked Feb 11 '14 21:02

membersound


People also ask

How do you find the element of multiple class names?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.

Can a div have multiple class names?

Absolutely, divs can have more than one class and with some Bootstrap components you'll often need to have multiple classes for them to function as you want them to. Applying multiple classes of course is possible outside of bootstrap as well. All you have to do is separate each class with a space.


2 Answers

Try this:

test = driver.findElement(By.xpath("//div[@class='value test']")); 
like image 44
barak manos Avatar answered Oct 13 '22 14:10

barak manos


I don't think barak manos's answer has fully explained it.

Imagine we have few elements as the followings:

  1. <div class="value test"></div>
  2. <div class="value test "></div>
  3. <div class="first value test last"></div>
  4. <div class="test value"></div>

How XPath matches

  • Match only 1 (exact match), barak's answer

    driver.findElement(By.xpath("//div[@class='value test']")); 
  • Match 1, 2 and 3 (match class contains value test, class order matters)

    driver.findElement(By.xpath("//div[contains(@class, 'value test')]")); 
  • Match 1, 2, 3 and 4 (as long as elements have class value and test)

    driver.findElement(By.xpath("//div[contains(@class, 'value') and contains(@class, 'test')]")); 

Also, in cases like this, Css Selector is always in favor of XPath (fast, concise, native).

  • Match 1

    driver.findElement(By.cssSelector("div[class='value test']")); 
  • Match 1, 2 and 3

    driver.findElement(By.cssSelector("div[class*='value test']")); 
  • Match 1, 2, 3 and 4

    driver.findElement(By.cssSelector("div.value.test")); 
like image 193
Yi Zeng Avatar answered Oct 13 '22 13:10

Yi Zeng