saya-ma
saya-ma

Reputation: 33

In JavaScript, how to use Xpath for String in any variable

This code works. But It's not what I want.

<div>XPath example</div>
<script>
const result = document.evaluate('//div', document, null, 6, null);
console.log(result.snapshotItem(0));
</script>

I want to use Xpath for strings from outside , but the following code is Null.

<script>
var string = "<div>XPath example</div>";
var doc = new DOMParser();
var htmlstring = doc.parseFromString(string, "text/html");
const result = htmlstring.evaluate('//div', document, null, 6, null);
console.log(result.snapshotItem(0));
</script>

How can I use Xpath in Javascript for a string get from the outside?

Upvotes: 1

Views: 977

Answers (1)

Rodik
Rodik

Reputation: 4092

You're passing document as the context node, when you should be passing htmlstring:

const result = htmlstring.evaluate('//div', htmlstring, null, 6, null);

Upvotes: 2

Related Questions