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?
You're passing document as the context node, when you should be passing htmlstring:
const result = htmlstring.evaluate('//div', htmlstring, null, 6, null);