Reputation: 486
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
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
Reputation: 33361
I'm not sure about the syntax, but I think this should work:
console.log($x('//h2').text());
Upvotes: 0