anonymousRey
anonymousRey

Reputation: 129

selenium click using span class or onclick

I am a newbie to java and selenium webdriver. I am having an issue clicking an image. Below is the page source.

<a href="javascript:void(0);">
<span class="HomeButton" onclick="javascript:onBtnHomeClick();"/>
</a>

I tried below codes but did not work and still getting the Unable to locate element error.

driver.findElement(By.xpath("//a[@onclick='onBtnHomeClick()']")).click();

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='js_AppContainer']/div[2]/div[1]/div[1]/span"))).click();


wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("HomeButton"))).click();

I have to click the homebutton. Any help would be much appreciated

Upvotes: 1

Views: 9316

Answers (2)

Makjb lh
Makjb lh

Reputation: 457

You simply need the correct locator IF your element will be eventually visible.

Xpath = "//span[contains(@class,'HomeButton') and contains(@onclick,'onBtnHomeClick')]"

Add wait as needed above exanmple, that should work.

Upvotes: 0

Guy
Guy

Reputation: 51009

I don't know why By.className("HomeButton") didn't work but you have errors in the other two.

In driver.findElement(By.xpath("//a[@onclick='onBtnHomeClick()']")).click(); the tag for onclick is <span> not <a>. It also not onBtnHomeClick() but javascript:onBtnHomeClick();

driver.findElement(By.xpath("//span[@onclick='javascript:onBtnHomeClick();']")).click();

If you want to use onBtnHomeClick() use contains

driver.findElement(By.xpath("//span[contains(@onclick, 'onBtnHomeClick')]")).click();

Or

driver.findElement(By.cssSelector("onclick*='onBtnHomeClick'")).click();

And in wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='js_AppContainer']/div[2]/div[1]/div[1]/span"))).click(); the <span> parent tag is <a>, not <div>

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='js_AppContainer']/div[2]/div[1]/div[1]/a/span"))).click();

Upvotes: 1

Related Questions