XPath for an element that contains another element with certain text?

Viewed 537

I know how to locate div inside the button:

//button/div[contains(text(),'Save')]

I'd like to know is it possible to locate any button which contains div with text "Save" inside?

<button class="PinBetterSave__Button" data-test-id="PinBetterSaveButton"><div class="_w7 _0 _1 _2 _wa _36 _d _b _6">Save</div></button>
2 Answers

You can try

//button[contains(div,'Save')]

to locate button with child div that contains specific text

Careful, the other answer, //button[contains(div,'Save')] works in this case, but be aware that it will fail when

  • The button contains a span or another or no element, rather than a div.
  • Other buttons exist with div elements whose string values contain the substring, "Save": "Save this", "Save that", "Jesus Saves", etc.

This XPath,

//button[normalize-space() = 'Save']

will select button elements whose space-normalized string value is exactly "Save".

Related