0

I'm trying to get elements with inner text that start with A new payment and end with was created.

<span>A new payment pi_123432 for $40.03 USD was created</span>
var xpath = "//span[starts-with(text(), 'A new payment') and ends-with(text(), 'was created')]";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

I'm getting not a valid XPath expression

Uncaught DOMException: Failed to execute 'evaluate' on 'Document': The string '//span[starts-with(text(), 'A new payment') and ends-with(text(), 'was created')]' is not a valid XPath expression.

When I break it down this xpath works:

var xpath = "//span[starts-with(text(), 'A new payment')]";

But this xpath throws the same error

var xpath = "//span[ends-with(text(), 'was created')]"

But I can't tell why.

I'm on chrome.

Dashiell Rose Bark-Huss
  • 2,173
  • 3
  • 28
  • 48

3 Answers3

1

ends-with is only in Xpath 2.0 and chrome uses Xpath 1.0

Xpath 1.0

var xpath = "//span[starts-with(text(), 'A new payment') and substring(text(), string-length(text()) - string-length('was created') + 1)  = 'was created']";
Dashiell Rose Bark-Huss
  • 2,173
  • 3
  • 28
  • 48
0

Using SaxonJS 2 and XPath 3.1:

var xpath = "//span[starts-with(., 'A new payment') and ends-with(., 'was created')]";
var matchingElements = SaxonJS.XPath.evaluate(xpath, document, { xpathDefaultNamespace : 'http://www.w3.org/1999/xhtml' });

console.log(matchingElements);
<script src="https://martin-honnen.github.io/Saxon-JS-2.4/SaxonJS2.rt.js"></script>

<span>A new payment pi_123432 for $40.03 USD was created</span>

See also the download page and the documentation of SaxonJS.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
0

But this xpath throws the same error

var xpath = "//span[ends-with(text(), 'was created')]"

But I can't tell why.

fn:ends-with() appeared for the first time in the XPath 2.0 specification. It isn't a standard XPath 1.0 function.

In XPath 1.0 to find the value of ends-with($s, $suffix) use:

substring($s, string-length($s) - string-length($suffix) + 1) =  $suffix
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431