Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to check if a text exists in a web page

Tags:

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.

like image 889
Sam Avatar asked May 14 '13 18:05

Sam


3 Answers

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.

like image 181
James Avatar answered Oct 02 '22 08:10

James


Try .search() Something like this:

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

Or instead of innerHTML, use textContent

like image 7
Milchkanne Avatar answered Oct 02 '22 08:10

Milchkanne


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.

like image 1
Lupus Avatar answered Oct 02 '22 08:10

Lupus