document.querySelector 通过 textContent

use*_*674 5 javascript dom

document.querySelector如果在textDocument执行代码时在视口上可用,那么在 JS 中是否可以仅通过给定的 textDocument选择第一个元素?


我正在寻找一种没有以下代码的方法,因为它会带出所有相关的 tagNames 并通过 textContent过滤它们,但我想通过文本内容选择它们,而不是过滤。

document.querySelectorAll('tagName').forEach( (e)=>{
    if (e.textContent.includes('Delete')) {
        e.click();
    }
});
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 5

没有针对 textContent 的 CSS 选择器

另外,正如您当前编写的代码一样,很容易获取该字符串的第一个元素textContent includes,它始终是document.documentElementor null

你应该让你的查询更严格一点。

您可能可以构建一个XPath查询到这种程度,但这最终会比您自己迭代所有节点慢。

因此,如果性能是一个问题,TreeWalker是最佳选择。

这是一个将通过 抓取元素的函数textContent
它有不同的可选参数,可以让你告诉

  • 如果查询应该严格(“string === textContent”,这是默认值),
  • 开始搜索的节点(默认为document.documentElement
  • 如果您只对没有孩子的元素感兴趣

function getElementByTextContent(str, partial, parentNode, onlyLast) {
  var filter = function(elem) {
    var isLast = onlyLast ? !elem.children.length : true;
    var contains = partial ? elem.textContent.indexOf(str) > -1 :
      elem.textContent === str;
    if (isLast && contains)
      return NodeFilter.FILTER_ACCEPT;
  };
  filter.acceptNode = filter; // for IE
  var treeWalker = document.createTreeWalker(
    parentNode || document.documentElement,
    NodeFilter.SHOW_ELEMENT, {
      acceptNode: filter
    },
    false
  );
  var nodeList = [];
  while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
  return nodeList;
}
// only the elements whose textContent is exactly the string
console.log('strict', getElementByTextContent('This should be found'))
// all elements whose textContent contain the string (your code)
console.log('partial', getElementByTextContent('This should', true))
// only the elements whose textContent is exactly the string and which are the last Element of the tree
console.log('strict onlyLast', getElementByTextContent('This should be found', false, null, true))
Run Code Online (Sandbox Code Playgroud)
<p><span>This should be found</span></p>
<span>This should only in partial mode</span><br>
<span>This must not be found</span>
<!-- p should not be found in onlyLast mode -->
Run Code Online (Sandbox Code Playgroud)


Gov*_*Rai 0

不,那里没有。document.querySelector只能接受描述一个或多个以逗号分隔的 CSS 选择器的字符串参数。您无法document.querySelector提供textDocument.

您必须检查不同节点的内容,其中一种方法是您在问题中描述的方式。