Search code examples
javaseleniumselenium-webdriverxpathwebdriverwait

How to identify element using ClassName and its Value using Java


HTML:

<div class="MuiGrid-root MuiGrid-grid-xs-12 karutaNameNam css-1uqhpru">Super Heros</div>

How to select the element using class = karutaNameNam and its Value = "Super Heros".


Solution

  • To identify the element with text as Super Heros you can use either of the following locator strategies:

    • cssSelector:

      WebElement element = driver.findElement(By.cssSelector("div[class*='MuiGrid-root'][class*='karutaNameNam']"));
      
    • xpath:

      WebElement element = driver.findElement(By.xpath("//div[contains(@class, 'karutaNameNam') and text()='Super Heros']"));
      

    Ideally to identify the element you need to induce WebDriverWait for the visibilityOfElementLocated and you can use either of the following locator strategies:

    • cssSelector:

      WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class*='MuiGrid-root'][class*='karutaNameNam']][value='emptyAssembly']")));
      
    • xpath:

      WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(@class, 'karutaNameNam') and text()='Super Heros']")));