Unable to trace an element by attribute or text

77 Views Asked by At

I am having trouble with clicking at an element of a menu which is written like this:

<div class="menu">
<ul class="tabs ctrlTabsProfile">
<li class="active" data-tab="tabDetail">User Details</li>
<li data-tab="tabEmail">Email</li>
<li data-tab="tabPass">Change password</li>
<li data-tab="tabAdress">Account Details</li>
</ul>
</div>

I have tried these:

driver.findElement(By.linkText("Account Details")).click();
driver.findElement(By.cssSelector("li[data-tab=tabAdress")).click();
driver.findElement(By.xpath("li[data-tab='tabAdress']")).click();

also tried listing the elements but got null only :

for(WebElement el : driver.findElements(By.cssSelector(".tabs.ctrlTabsProfile"))) {

        try {
            assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*Account Details[\\s\\S]*$"));
        } catch (Error e) {
            System.out.println("Not found: \"Account Details\".");
          }

    String s = el.getAttribute("data-tab");
    System.out.println(s);
    if(s.equals("tabAdress")) {
        driver.findElement(By.xpath("li[data-tab='tabAdress']")).click();
    }
   }

Solutions? Sugestions? Errors?

2

There are 2 best solutions below

1
On BEST ANSWER

Well, for one, your xpath selector is incorrect.

driver.findElement(By.xpath("li[data-tab='tabAdress']")).click();

should be:

driver.findElement(By.xpath("//li[@data-tab='tabAdress']")).click();

edit:

And your css selector is incorrect as well.

driver.findElement(By.cssSelector("li[data-tab=tabAdress")).click();

should be:

driver.findElement(By.cssSelector("li[data-tab='tabAdress']")).click();

edit #2:

and:

driver.findElement(By.linkText("Account Details")).click();

will only work if the element is a link, which in this case it is not.

1
On

Aholt is right, driver.findElements(By.cssSelector(".tabs.ctrlTabsProfile")) will return only ul elements. To access all <li>, you could try:

driver.findElements(By.cssSelector("ul.tabs.ctrlTabsProfile li.active"))