[英]Why does the content return the same object on JavaScript?
在下面的 Javascript 代码中,它在 Chrome 控制台上运行(网页只是在 Google 上的随机搜索结果):
var result = document.getElementsByClassName('g')
var xpath = "//h3[contains(text(),'wrong')]";
for (let i = 0; i < result.length; i++) {
var r = document.evaluate(xpath, result[i], null, XPathResult.FIRST_ORDERED_NODE_TYPE, null)
console.log(i);
console.log(r.singleNodeValue);
result[i].style.display = 'none';
}
我想在每个相关的搜索结果项目上搜索一个关键字,如果有,从结果中隐藏该项目。 然而,上面的输出似乎重复了包含关键字的搜索结果,即使在我的测试样本中,关键字只包含在一个项目中。
0
<h3 class="LC30li DRV0Md">Why is this code not working</h3>
1
<h3 class="LC30li DRV0Md">Why is this code not working</h3>
..... (up to the last search item)
所以循环正在运行,但似乎r.singleNodeValue
总是返回相同的对象。
我想知道为什么它不显示每个项目的结果。
来自Document.evaluate MDN 文档:
document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);
注意上面的
document.body
已被用作上下文而不是document
因此 XPath 从 body 元素开始。 (在这个例子中,"."
很重要,它表明查询应该从上下文节点document.body
。如果"."
被省略(离开//h2
),查询将从根节点开始( html),这会更浪费。)
所以我认为你只需要添加一个 '.' 在您的 xpath 开始时。 在这里你总是得到整个文档中匹配的第一个元素,忽略你提供的上下文元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.