Find div element by multiple class names?

membersound picture membersound · Feb 11, 2014 · Viewed 76.6k times · Source

<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;

Answer

Yi Zeng picture Yi Zeng · Feb 11, 2014

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"));