【问题标题】:In JavaScript, how to use Xpath for String in any variable在 JavaScript 中,如何在任何变量中为 String 使用 Xpath
【发布时间】:2021-08-09 14:26:51
【问题描述】:

此代码有效。 但这不是我想要的。

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

我想对外部字符串使用 Xpath,但以下代码为 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>

如何在 Javascript 中使用 Xpath 从外部获取字符串?

【问题讨论】:

    标签: javascript xpath document.evaluate


    【解决方案1】:

    您将 document 作为上下文节点传递,而您应该传递 htmlstring

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 2013-07-10
      • 2023-01-21
      • 2018-01-30
      相关资源
      最近更新 更多