Javascript .querySelector找到< div>通过innerTEXT [英] Javascript .querySelector find <div> by innerTEXT
问题描述
如何找到包含特定文字的DIV?例如:
How can I find DIV with certain text? For example:
<div>
SomeText, text continues.
</div>
尝试使用以下内容:
var text = document.querySelector('div[SomeText*]').innerTEXT;
alert(text);
但是当然它不起作用。我怎么能这样做?
But ofcourse it will not work. How can I do it?
推荐答案
OP的问题是关于普通 JavaScript 而不是 jQuery 。
虽然有很多答案我喜欢@Pawan Nogariya的答案,但请检查这个替代品。
OP's question is about plain JavaScript and not jQuery. Although there are plenty of answers and I like @Pawan Nogariya answer, please check this alternative out.
你可以使用 XPATH 在JavaScript中。有关MDN文章此处的更多信息。
You can use XPATH in JavaScript. More info on the MDN article here.
document.evaluate()
方法评估XPATH查询/表达式。因此,您可以在那里传递XPATH表达式,遍历HTML文档并找到所需的元素。
The document.evaluate()
method evaluates an XPATH query/expression. So you can pass XPATH expressions there, traverse into the HTML document and locate the desired element.
在XPATH中,您可以通过文本节点选择一个元素,如下所示,获取具有以下文本节点的 div
。
In XPATH you can select an element, by the text node like the following, whch gets the div
that has the following text node.
//div[text()="Hello World"]
要获取包含某些文本的元素,请使用以下:
To get an element that contains some text use the following:
//div[contains(., 'Hello')]
XPATH中的包含()
方法将节点作为第一个参数和要搜索的文本作为第二个参数。
The contains()
method in XPATH takes a node as first parameter and the text to search for as second parameter.
检查此插件此处,这是在JavaScript中使用XPATH的示例
Check this plunk here, this is an example use of XPATH in JavaScript
以下是代码段:
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元素并根据需要进行修改。
As you can see, I can grab the HTML element and modify it as I like.
这篇关于Javascript .querySelector找到< div>通过innerTEXT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!