Question

There are several questions out there that resemble this one. But I did not found this exact question on SO. (nor the answer elsewhere).

I just need to know if a string is showing AT LEAST ONCE. It might be possible that the string occurs more than once in the HTML, that it is hidden one time and showing another time.

It's about visibility in the page, not necessarily in the viewport. Thus if you have to scroll to view it, that is OK too.

UPDATE: I know of :contains and is(":visible") that's not the problem. Elements can be nested deep of course, and it has to work in all circumstances.

Was it helpful?

Solution

The following should work, but it is not the most efficient solution though:

$("body, body *").contents().filter(function () {
    return this.nodeType === 3 && this.nodeValue.indexOf("Foo & Bar") >= 0;
}).parent(":visible");

This code:

  • Locates all text nodes in the document that contain the specified string 1
  • And checks if their parent is visible 2

1 This means the deepest node that contains the string. The :contains selector would be useless because it could return a visible element (in fact a branch of elements) that contains an invisible child that contains the specified string.

2 An element is visible if its parents are visible as well

OTHER TIPS

You can use :contains over your body element together with length, which count the number of matches.

if($('body:contains("demo")').length){
    alert("The world exists");
}else{
    alert("The world doesn't exist");   
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top