我如何能找到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);
当然,这是行不通的。我该怎么做呢?
当前回答
我也有类似的问题。
函数返回包含arg文本的所有元素。
这对我来说很管用:
function getElementsByText(document, str, tag = '*') {
return [...document.querySelectorAll(tag)]
.filter(
el => (el.text && el.text.includes(str))
|| (el.children.length === 0 && el.outerText && el.outerText.includes(str)))
}
其他回答
如果你不想使用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的父节点。
OP的问题是关于纯JavaScript而不是jQuery。 虽然有很多答案,我喜欢@Pawan Nogariya的答案,但请看看这个替代答案。
你可以在JavaScript中使用XPATH。更多关于MDN文章的信息请点击这里。
document.evaluate()方法对XPATH查询/表达式求值。因此,您可以在那里传递XPATH表达式,遍历HTML文档并找到所需的元素。
在XPATH中,您可以通过如下所示的文本节点选择一个元素,它将获得具有以下文本节点的div。
//div[text()="Hello World"]
要获得一个包含一些文本的元素,使用以下方法:
//div[contains(., 'Hello')]
XPATH中的contains()方法将节点作为第一个参数,将要搜索的文本作为第二个参数。
看这里,这是JavaScript中XPATH的例子
下面是一个代码片段:
var headings = document.evaluate("//h1[contains(., 'Hello')]", document, null, XPathResult.ANY_TYPE, null );
var thisHeading = headings.iterateNext();
console.log(thisHeading); // Prints the html element in console
console.log(thisHeading.textContent); // prints the text content in console
thisHeading.innerHTML += "<br />Modified contents";
如您所见,我可以获取HTML元素并按我喜欢的方式修改它。
谷歌有这作为顶部结果为那些谁需要找到一个节点与特定的文本。 通过更新,节点列表现在在现代浏览器中是可迭代的,而不必将其转换为数组。
解决方案可以像这样使用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
}
});
当一个普通的选择器不能选择一个节点时,我可以在节点列表中查找/替换文本,所以我必须一个接一个地过滤每个节点以检查它是否有针。
由于数据属性中的文本长度没有限制,所以请使用数据属性!然后你可以使用常规的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选择器的范围以提高性能。
该解决方案实现如下功能:
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> .