Xpath for button having text as 'New'

70,602

Solution 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

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

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')]
Share:
70,602
HemaSundar
Author by

HemaSundar

Updated on April 27, 2022

Comments

  • HemaSundar
    HemaSundar about 2 years

    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?

  • Ian Roberts
    Ian Roberts about 10 years
    Technically this will end up clicking the span rather than the button but the event will bubble up so it will have the required effect.
  • Stephan
    Stephan about 10 years
    @IanRoberts Thks for your comment ;)
  • hfontanez
    hfontanez about 2 years
    You could also use the path to the span containing the text inside the predicate.