Select 个页面上的节点(按文本片段)

Select nodes on page by text fragment

Select页面上的所有节点,其中的文本包含特定短语。 例如,在DOM结构中有如下节点:

<div class="one">Lorem ipsum dolor sit amet.</div>
<option class="two">Lorem ipsum dolor sit amet.</option>
<div class="three">Example: Lorem ipsum dolor sit amet.</div>
<label class="four">Lorem ipsum dolor sit amet.</label>

我需要选择满足短语 'Example:' 的节点。 这样的节点可能有任何 类 或没有... 你告诉我如何解决这个问题?

这是一个 returns 节点文本与正则表达式匹配的元素的函数:

function getNodeByTextContent(regEx) {
  var all = document.querySelectorAll('*');
  return Array.prototype.slice.call(all).filter(function (el) { 
    return el.textContent.match(regEx);
  });
}

//EG: all nodes where the text begins with 'example'
var matchedNodes = getNodeByTextContent(/^example/i);
for (i = 0; i < matchedNodes.length; ++i) {
  matchedNodes[i].style.color = "green";
}
<div class="one">Lorem ipsum dolor sit amet.</div>
<option class="two">Lorem ipsum dolor sit amet.</option>
<div class="three">Example: Lorem ipsum dolor sit amet.</div>
<label class="four">Lorem ipsum dolor sit amet.</label>

我能想到的两个方案

首先是获取所有节点,然后循环 运行 测试。

另一种是使用 XPath 检索节点

//*[contains(., "Example")]

select 所有包含字符串 "Example" 的元素都在其中

请注意,这将包括父元素(因为它们还包括字符串)如果您想要纯叶元素:

//*[contains(., "Example") and not(child::*)]

会这样做,但不会检索诸如

之类的元素
<p>Example: this is an <em>important</em> example</p>