'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>
</button>

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"))
    {
        w.click();
        break;
    }
}

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



Solution 1:[1]

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")

Solution 2:[2]

Try this xpath instead:

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

Demo

http://www.xpathtester.com/xpath/ff393b48183ee3f373d4ca5f539bedf2


EDIT

Following comment from @Ian Roberts, you can use the following xpath expression instead if the click on the button element is important:

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

Solution 3:[3]

The very simple solution for the above issue is to use span with option contains(text(),'').

You can use the following xpath code

//span[contains(text(),'New')]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 Wahyu Kristianto