我如何能找到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);
当然,这是行不通的。我该怎么做呢?
当前回答
由于数据属性中的文本长度没有限制,所以请使用数据属性!然后你可以使用常规的css选择器来选择你的元素(s)像OP想要的。
for (document.querySelectorAll("*")的常量元素){ element.dataset.myInnerText = element.innerText; } 文档。querySelector(“* [data-my-inner-text = '不同的文本。']”).style.color =“蓝色”; <div> . SomeText, text continue .</div> . SomeText, text continue 不同文本< div >。< / div >
理想情况下,您可以在文档加载时完成数据属性设置部分,并缩小querySelectorAll选择器的范围以提高性能。
其他回答
如果你不想使用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的父节点。
你可以使用这个非常简单的解决方案:
Array.from(document.querySelectorAll('div'))
.find(el => el.textContent === 'SomeText, text continues.');
from将把NodeList转换为一个数组(有多种方法可以做到这一点,如展开操作符或切片) 结果现在是一个数组,允许使用数组。Find方法,然后可以放入任何谓词。你也可以用正则表达式或任何你喜欢的东西检查textContent。
注意Array.from和Array.from。find是ES2015的特性。在没有转译器的情况下,与IE10等旧浏览器兼容:
Array.prototype.slice.call(document.querySelectorAll('div'))
.filter(function (el) {
return el.textContent === 'SomeText, text continues.'
})[0];
该解决方案实现如下功能:
Uses the ES6 spread operator to convert the NodeList of all divs to an array. Provides output if the div contains the query string, not just if it exactly equals the query string (which happens for some of the other answers). e.g. It should provide output not just for 'SomeText' but also for 'SomeText, text continues'. Outputs the entire div contents, not just the query string. e.g. For 'SomeText, text continues' it should output that whole string, not just 'SomeText'. Allows for multiple divs to contain the string, not just a single div.
[…document.querySelectorAll('div')] //获取数组中所有div .map(div => div. innerhtml) //获取它们的内容 .filter(txt => txt.includes('SomeText')) //只保留包含查询的内容 .forEach(txt => console.log(txt));//输出这些的全部内容 <div> . SomeText, text continue .</div> . SomeText, text continue <div>不在这个div中 这里是更多的SomeText.</div> .
我一直在寻找一种使用Regex来做类似事情的方法,并决定构建我自己的东西,如果其他人正在寻找类似的解决方案,我想分享它。
function getElementsByTextContent(tag, regex) {
const results = Array.from(document.querySelectorAll(tag))
.reduce((acc, el) => {
if (el.textContent && el.textContent.match(regex) !== null) {
acc.push(el);
}
return acc;
}, []);
return results;
}
下面是XPath方法,但是使用了最少的XPath术语。
基于元素属性值的常规选择(用于比较):
// for matching <element class="foo bar baz">...</element> by 'bar'
var things = document.querySelectorAll('[class*="bar"]');
for (var i = 0; i < things.length; i++) {
things[i].style.outline = '1px solid red';
}
基于元素内文本的XPath选择。
// for matching <element>foo bar baz</element> by 'bar'
var things = document.evaluate('//*[contains(text(),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
things.snapshotItem(i).style.outline = '1px solid red';
}
这里是不区分大小写的,因为文本更不稳定:
// for matching <element>foo bar baz</element> by 'bar' case-insensitively
var things = document.evaluate('//*[contains(translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"bar")]',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0; i < things.snapshotLength; i++) {
things.snapshotItem(i).style.outline = '1px solid red';
}