yoman
yoman

Reputation: 13

Select element with a changing Id string using XPath

I have a textarea control with an Id that goes something like this:

<textarea id="NewTextArea~~51887~~1" rows="2"/>

And the xpath that has worked before has been

//textarea[@id, "NewTextArea~~51887~~1"]

But now the '51887' portion of the id is become diverse (changing every time) so I need to select the NewtextArea~~*~~1 element without actually specifying the number. Is there a way I can wildcard part of the string so that it will match a particular pattern? I tried using starts-with and ends-with but couldn't get it to work:

//textarea[starts-with(@id, 'NewTextArea~~') and ends-with(@name, '~~1')]

Bare in mind there are other fields with the difference being the number on the end.

Any advice or guidance would be greatly appreciated :)

Upvotes: 1

Views: 599

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

I tried using starts-with and ends-with but couldn't get it to work:

//textarea[starts-with(@id, 'NewTextArea~~') and ends-with(@name, '~~1')]

ends-with() is available as a standard function only in XPath 2.0 and you seem to be using XPath 1.0.

Use:

//textarea
   [starts-with(@id, 'NewTextArea~~')
  and
   substring(@id, string-length(@id) - 2) = '~~1'
   ]

Explanation:

See the answer to this question, for how to implement ends-with() in XPath 1.0:

https://stackoverflow.com/a/405507/36305

Upvotes: 1

Related Questions