Javascript:如何检查网页中是否存在文本 [英] Javascript: how to check if a text exists in a web page

查看:143
本文介绍了Javascript:如何检查网页中是否存在文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设字符串Done successfuly显示在网页的某个位置,有没有办法知道这个字符串是否仅使用javascript存在?
谢谢。

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.

推荐答案

更多细节会有所帮助。可能有更好的方法。但鉴于您提供的信息,这是最好的:

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...
}

如果你知道ID或类名,或者可以选择直接包含文本的元素(例如 h1#someHeading span ... )那么你应该这样做,因为它会更高效,通常更清洁。

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.

编辑值得注意的是:这种方法也会在SCRIPT和STYLE标签中拾取文本,这可能不是你想要的。 textContent innerText 在浏览器中也存在各种怪癖。 有关详情,请参阅此处

EDIT Worth 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.

这篇关于Javascript:如何检查网页中是否存在文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆