我如何能找到DIV与某些文本?例如:
<div>
SomeText, text continues.
</div>
试图使用这样的东西:
var text = document.querySelector('div[SomeText*]').innerTEXT;
alert(text);
当然,这是行不通的。我该怎么做呢?
我如何能找到DIV与某些文本?例如:
<div>
SomeText, text continues.
</div>
试图使用这样的东西:
var text = document.querySelector('div[SomeText*]').innerTEXT;
alert(text);
当然,这是行不通的。我该怎么做呢?
当前回答
如果你不想使用jquery或类似的东西,那么你可以试试这个:
function findByText(rootElement, text){
var filter = {
acceptNode: function(node){
// look for nodes that are text_nodes and include the following string.
if(node.nodeType === document.TEXT_NODE && node.nodeValue.includes(text)){
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
var nodes = [];
var walker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT, filter, false);
while(walker.nextNode()){
//give me the element containing the node
nodes.push(walker.currentNode.parentNode);
}
return nodes;
}
//call it like
var nodes = findByText(document.body,'SomeText');
//then do what you will with nodes[];
for(var i = 0; i < nodes.length; i++){
//do something with nodes[i]
}
在数组中拥有包含文本的节点后,就可以对它们进行操作。比如提醒每个人或打印到控制台。需要注意的是,这可能并不一定会抓取div本身,这将抓取拥有您正在寻找的文本的textnode的父节点。
其他回答
如果你不想使用jquery或类似的东西,那么你可以试试这个:
function findByText(rootElement, text){
var filter = {
acceptNode: function(node){
// look for nodes that are text_nodes and include the following string.
if(node.nodeType === document.TEXT_NODE && node.nodeValue.includes(text)){
return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
}
}
var nodes = [];
var walker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT, filter, false);
while(walker.nextNode()){
//give me the element containing the node
nodes.push(walker.currentNode.parentNode);
}
return nodes;
}
//call it like
var nodes = findByText(document.body,'SomeText');
//then do what you will with nodes[];
for(var i = 0; i < nodes.length; i++){
//do something with nodes[i]
}
在数组中拥有包含文本的节点后,就可以对它们进行操作。比如提醒每个人或打印到控制台。需要注意的是,这可能并不一定会抓取div本身,这将抓取拥有您正在寻找的文本的textnode的父节点。
谷歌有这作为顶部结果为那些谁需要找到一个节点与特定的文本。 通过更新,节点列表现在在现代浏览器中是可迭代的,而不必将其转换为数组。
解决方案可以像这样使用forEach。
var elList = document.querySelectorAll(".some .selector");
elList.forEach(function(el) {
if (el.innerHTML.indexOf("needle") !== -1) {
// Do what you like with el
// The needle is case sensitive
}
});
当一个普通的选择器不能选择一个节点时,我可以在节点列表中查找/替换文本,所以我必须一个接一个地过滤每个节点以检查它是否有针。
因为你已经在javascript中要求它,所以你可以有这样的东西
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
return RegExp(text).test(element.textContent);
});
}
然后像这样叫它
contains('div', 'sometext'); // find "div" that contain "sometext"
contains('div', /^sometext/); // find "div" that start with "sometext"
contains('div', /sometext$/i); // find "div" that end with "sometext", case-insensitive
在2021年遇到这个问题时,我发现使用XPATH太复杂了(需要学习其他东西),不适合做一些应该相当简单的事情。
我想到了这个:
function querySelectorIncludesText (selector, text){
return Array.from(document.querySelectorAll(selector))
.find(el => el.textContent.includes(text));
}
用法:
querySelectorIncludesText('button', 'Send')
请注意,我决定使用包含,而不是严格的比较,因为这是我真正需要的,请随意调整。
如果你想支持所有浏览器,你可能需要这些腻子:
/**
* String.prototype.includes() polyfill
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
* @see https://vanillajstoolkit.com/polyfills/stringincludes/
*/
if (!String.prototype.includes) {
String.prototype.includes = function (search, start) {
'use strict';
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp');
}
if (start === undefined) {
start = 0;
}
return this.indexOf(search, start) !== -1;
};
}
这里已经有很多很棒的解决方案了。但是,为了提供一个更精简的解决方案,并且更符合querySelector行为和语法的思想,我选择了一个用几个原型函数扩展Object的解决方案。这两个函数都使用正则表达式来匹配文本,但是,字符串可以作为松散搜索参数提供。
简单地实现以下函数:
// find all elements with inner text matching a given regular expression
// args:
// selector: string query selector to use for identifying elements on which we
// should check innerText
// regex: A regular expression for matching innerText; if a string is provided,
// a case-insensitive search is performed for any element containing the string.
Object.prototype.queryInnerTextAll = function(selector, regex) {
if (typeof(regex) === 'string') regex = new RegExp(regex, 'i');
const elements = [...this.querySelectorAll(selector)];
const rtn = elements.filter((e)=>{
return e.innerText.match(regex);
});
return rtn.length === 0 ? null : rtn
}
// find the first element with inner text matching a given regular expression
// args:
// selector: string query selector to use for identifying elements on which we
// should check innerText
// regex: A regular expression for matching innerText; if a string is provided,
// a case-insensitive search is performed for any element containing the string.
Object.prototype.queryInnerText = function(selector, text){
return this.queryInnerTextAll(selector, text)[0];
}
实现了这些函数后,现在可以进行如下调用:
document.queryInnerTextAll('div.link', 'go'); This would find all divs containing the link class with the word go in the innerText (eg. Go Left or GO down or go right or It's Good) document.queryInnerText('div.link', 'go'); This would work exactly as the example above except it would return only the first matching element. document.queryInnerTextAll('a', /^Next$/); Find all links with the exact text Next (case-sensitive). This will exclude links that contain the word Next along with other text. document.queryInnerText('a', /next/i); Find the first link that contains the word next, regardless of case (eg. Next Page or Go to next) e = document.querySelector('#page'); e.queryInnerText('button', /Continue/); This performs a search within a container element for a button containing the text, Continue (case-sensitive). (eg. Continue or Continue to Next but not continue)