1

In Chrome's Debugger's Console window, I'd like to convert (sort of flatten) an array to string, like this:

<div class="foo">
  <div class="bar">a</div>
  <div class="bar">b</div>
</div>

and get this result: a b

This works but seems like a hack:

var arr = $x('//*[@class="foo"]/descendant-or-self::*/text()')
for (i in arr) { console.log(arr[i].data); };

But text(), of course, returns an array, whereas I just want the text.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
mellow-yellow
  • 1,670
  • 1
  • 18
  • 38

2 Answers2

2

To get all of the text of an XML document in XPath 1.0, use string():

> $x("string(/)")
< '\n  a\n  b\n'

To normalize whitespace (again, XPath 1.0), use normalize-space():

> $x("normalize-space(/)")
< 'a b'

Substitute any element-selecting XPath (such as //*[@class="foo"]) for / to limit the text to descendants of (the first of, in XPath 1.0) the selected elements.

Note that string-join() requires XPath 2.0, which is not supported in Chrome.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
0

Try this one to get single string that consists of both child text values joined with space char

string-join(//div[@class="bar"], " ")

or

string(//div[@class="foo"])

to get string representation of parent node

JaSON
  • 4,843
  • 2
  • 8
  • 15
  • In the Chrome (103.0.5060.114) debugger console, I get an error no matter what arguments I send to string-join, for example: `string-join("hi") VM9617:1 Uncaught ReferenceError: string is not defined at :1:1` – mellow-yellow Jul 21 '22 at 23:00
  • As kjhughes mentioned in his answer,`string-join()` is an XPath 2.0 function and therefore not available in the Browser's XPath 1.0 implementation. – Thomas W Aug 08 '22 at 04:27