0brine
0brine

Reputation: 486

XPath text() returns 2 Values how to combine them to one

I have this:

const $x = xp => {
  const snapshot = document.evaluate(
    xp, document, null, 
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
  );
  return [...Array(snapshot.snapshotLength)]
    .map((_, i) => snapshot.snapshotItem(i))
  ;
};

console.log($x('//h2/text()[1]'));
console.log($x('//h2/text()[2]'));
<h2 _ngcontent-gbb-c105="" class="text-center">HERZLICH WILLKOMMEN <br _ngcontent-gbb-c105=""> BEI DEINER ANKER APP</h2>

is there a way to get both text()[1] and text()[2] joined together so I could do something like this: //*[text()='HERZLICH WILLKOMMEN BEI DEINER ANKER APP']

Upvotes: 0

Views: 181

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167506

I would simply select the h2 element and then read out its textContent property:

const $x = xp => {
  const snapshot = document.evaluate(
    xp, document, null, 
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
  );
  return [...Array(snapshot.snapshotLength)]
    .map((_, i) => snapshot.snapshotItem(i))
  ;
};

console.log($x('//h2')[0].textContent);
<h2 _ngcontent-gbb-c105="" class="text-center">HERZLICH WILLKOMMEN <br _ngcontent-gbb-c105=""> BEI DEINER ANKER APP</h2>

Or you can use the XPath expression string((//h2)[1]) but obviously your JavaScript code to use the XPath API then would need to be changed to use a different result type:

const text = document.evaluate('string((//h2)[1])', document, null, XPathResult.STRING_TYPE, null).stringValue;

console.log(text);
<h2 _ngcontent-gbb-c105="" class="text-center">HERZLICH WILLKOMMEN <br _ngcontent-gbb-c105=""> BEI DEINER ANKER APP</h2>

Upvotes: 1

Prophet
Prophet

Reputation: 33361

I'm not sure about the syntax, but I think this should work:

console.log($x('//h2').text());

Upvotes: 0

Related Questions