Home > Software design >  How to select all text via XPath in Chrome console
How to select all text via XPath in Chrome console

Time:07-22

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

<div >
  <div >a</div>
  <div >b</div>
</div>

and get this result: a b

This works but seems like a hack:

var arr = $x('//*[@]/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.

CodePudding user response:

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

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

or

string(//div[@])

to get string representation of parent node

CodePudding user response:

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 //*[@]) 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.

  • Related