21

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.

Sam
  • 487
  • 4
  • 12
  • 31
  • Not sure what you are asking, or what you tried... – Naftali May 14 '13 at 18:17
  • 3
    Yes there is, but it's probably not the best solution to whatever you're trying to do. It might be more useful to explain your full problem and what you have tried so far to solve it. – James Montagne May 14 '13 at 18:17
  • 3
    The purpose of this site is to help you fix code that you have written. The first part is you need to write code. Meet us have way. – Cam May 14 '13 at 18:18

3 Answers3

43

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.

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.

Community
  • 1
  • 1
James
  • 109,676
  • 31
  • 162
  • 175
7

Try .search() Something like this:

document.body.innerHTML.search("Done successfully!");

Or instead of innerHTML, use textContent

Milchkanne
  • 111
  • 1
  • 8
1

The easiest way of doing this is using jquery's contains selector:

if($("*:contains('Hello World')").length > 0)
    console.log('yeah baby');

This way also gives you the container element of the text.

Lupus
  • 1,519
  • 3
  • 21
  • 38
  • 10
    FWIW, this particular selector will use Sizzle (as its not a natively supported selector) and will select every single element on the page, and will then loop through *every* element checking for the text. This is not exactly... efficient. – James May 14 '13 at 18:48