user3196126 user3196126 - 1 year ago 78
Java Question

How to click on Javascript button in Selenium with no ID (Java)?

I'm setting up a program in Java with Selenium.

At the start of the program, a Chrome extension I'm using with the program loads up with the Chrome instance.

Chrome then navigates to that page, selects all the boxes, and is supposed to click a button on the page that appears because of the extension.

So I am trying to click that button, but it's a Javascript button that comes on the page through the extension. There is no ID that I can use explicitly though.

When I inspect the element, all I see is this:

<a href="javascript:void(0);" class="selected button-task"
style="width: 140px; margin-left: 5px; height: 23px;">
<img src="websiteimage.png here" width="20px">Selected Task</a>

Unlike the other stuff I can click on, there is no type (checkboxes, button, etc) or a specific ID I can seek out. But it is important I click this button. What should I do?

I get this error when I use this:

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector:
Unable to locate an element with the xpath expression //a[contains@class,'selected'] and contains(@class, 'repost-selected button-task') and contains(text(), 'Repost Selected') because of the following error:

SyntaxError: Failed to execute 'evaluate' on 'Document':
The string '//a[contains@class,'selected'] and contains(@class, 'repost-selected button-task') and contains(text(), 'Repost Selected')' is not a valid XPath expression.


Answer Source

I figured out how to solve it:

WebElement extensionBox = driver.findElement(By.xpath(".//a[normalize-space()='Selected Task']"));

Actions actionsTwo = new Actions(driver);
JavascriptExecutor jseTwo = (JavascriptExecutor) driver;
jseTwo.executeScript("arguments[0].click()", extensionBox);

The other answers weren't working because they either wouldn't find the object on the page, or would give compile errors

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download