Javascript:如何检查网页中是否存在文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16550069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: how to check if a text exists in a web page
提问by Sam
Let's say the String "Done successfuly" is displayed somewhere in a webpage , is there a way to know if this string exist using javascript only ? Thanks.
假设字符串“成功完成”显示在网页的某处,有没有办法仅使用 javascript 来知道此字符串是否存在?谢谢。
回答by James
More details would help. There may be better ways. But this is the best given what information you've provided:
更多细节会有所帮助。可能有更好的方法。但鉴于您提供的信息,这是最好的:
if (
(
document.documentElement.textContent || document.documentElement.innerText
).indexOf('Done successfuly') > -1
) {
// Do something...
}
If you know the ID or class-name or can otherwise select the element that directly contains the text (e.g. h1#someHeading span ...
) then you should probably do that as it will be more performant and generally a cleaner approach.
如果您知道 ID 或类名,或者可以以其他方式选择直接包含文本的元素(例如h1#someHeading span ...
),那么您可能应该这样做,因为它会提高性能并且通常是一种更清晰的方法。
EDITWorth noting: This approach will pick up text within SCRIPT and STYLE tags too, which is probably not what you want. Both textContent
and innerText
have various quirks across browsers too. See this for more info.
编辑值得注意:这种方法也会在 SCRIPT 和 STYLE 标签中提取文本,这可能不是你想要的。双方textContent
并innerText
具有跨浏览器的各种怪癖了。请参阅此了解更多信息。
回答by Milchkanne
Try .search() Something like this:
尝试 .search() 这样的事情:
document.body.innerHTML.search("Done successfully!");
Or instead of innerHTML, use textContent
或者代替innerHTML,使用textContent
回答by Lupus
The easiest way of doing this is using jquery's contains selector:
最简单的方法是使用 jquery 的 contains 选择器:
if($("*:contains('Hello World')").length > 0)
console.log('yeah baby');
This way also gives you the container element of the text.
这种方式还为您提供了文本的容器元素。