HemaSundar HemaSundar - 3 months ago 6
Java Question

Xpath for button having text as 'New'

In our application almost in every screen we have a button with text 'New', Here is the html source for one of the button:

<button id="defaultOverviewTable:j_id54" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover" type="submit" name="defaultOverviewTable:j_id54" role="button" aria-disabled="false">
<span class="ui-button-text ui-c">New</span>

I have tried using the below statement to click on the button:

driver.findElement(By.xpath("//button[[@type, 'submit'] and [text()='New']]")).click();

But this was not working

org.openqa.selenium.InvalidSelectorException: The given selector //button[[@type= 'submit'] and [text()='New']] is either invalid or does not result in a WebElement.

Currently I am using the below code to click on the button:

List<WebElement> allButt = driver.findElements(By.tagName("button"));
for (WebElement w : allButt)
if (w.getText().matches("New"))

As I have almost 150 buttons in the page. Is there any other way?


Your xpath syntax is wrong - you don't need the inner set of square brackets - but even if you fix this:

//button[@type, 'submit' and text()='New']

it won't select what you want it to. The problem is that the "New" is not text contained directly in the button element but is inside a child span element. If instead of text() you just use . then you can check the whole string value of the element (the concatenation of all descendant text nodes at whatever level)

//button[@type='submit' and contains(., 'New')]

Or check span instead of text():

//button[@type='submit' and span='New']

(submit buttons containing a span whose value is "New")