简体   繁体   English

使用XPath在节点之后查找文本节点

[英]Find text node after a node with XPath

I am trying to use document.evaluate to find text nodes matching my query. 我正在尝试使用document.evaluate查找与我的查询匹配的文本节点。 The issue I found is that with the XPath I am using, it is not finding text nodes that follow another element. 我发现的问题是,使用的XPath找不到在另一个元素之后的文本节点。 For example, given these conditions ( jsFiddle ): 例如,鉴于以下条件( jsFiddle ):

HTML 的HTML

<div><p>$100</p></div>
<p>Test test <span>test</span> $100 test</p>

Javascript Java脚本

var item,
  indx = 0,
  items = document.evaluate('//*[contains(text(),"$")]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

while (item = items.snapshotItem(indx++)) {
  if (item.nodeName !== 'SCRIPT') {
    console.log(item.textContent);
  }
}

This XPath only finds the first $ , the second isn't found because of the <span> in the middle. 此XPath仅找到第一个$ ,由于中间的<span> ,因此找不到第二个。

So my question is how can I change the javascript (not the HTML) to find both matches? 所以我的问题是如何更改javascript(而不是HTML)以找到两个匹配项?

将XPath表达式更改为//*[text()[contains(.,"$")]]因为这样会选择具有包含$符号的文本子节点的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM