如果 textDocument
在代码执行时在视口(viewport)上可用,是否可以在 JS 中仅通过给定的 textDocument 选择带有 document.querySelector
的第一个元素执行了吗?
我正在寻找一种没有以下代码的方法,因为它会带出所有相关的标签名称并通过 textContent 过滤它们,但我想选择 他们按文本内容,而不是过滤。
document.querySelectorAll('tagName').forEach( (e)=>{
if (e.textContent.includes('Delete')) {
e.click();
}
});
最佳答案
没有 CSS selector targeting on textContent .
此外,由于您的代码当前已编写,因此很容易获取 textContent
包含
此字符串的第一个元素,它将始终为 document.documentElement
或 null
。
您应该使查询更严格一些。
你或许可以构建一个 XPath查询到这个程度,但这最终会比自己迭代所有节点慢。
所以如果性能是个问题,一个TreeWalker是要走的路。
这是一个通过textContent
抓取元素的函数。
它有不同的可选参数,可以让你告诉
- 如果查询应该是严格的(默认为“string === textContent”),
- 开始搜索的节点(默认为
document.documentElement
) - 如果你只对没有 child 的元素感兴趣
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))
<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 -->
关于javascript - document.querySelector 通过 textContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46086917/