-1

I'm trying to find a text on a loaded page and if the text matched then I should get alerted

<script type='text/javascript'>
  window.onload = function() {

    if ((document.documentElement.textContent || document.documentElement.innerText).indexOf("John") > -1) {
      alert("Matched");
    }
  };
</script>


<body>
  <p> Hello! John is here </p>
</body>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
rooot_999
  • 366
  • 2
  • 3
  • 13

4 Answers4

2

Change || operator to && operator in your condition.

if ((document.documentElement.textContent && document.documentElement.innerText).indexOf("John") > -1) {
         alert("Matched!");
}
Jon P
  • 19,442
  • 8
  • 49
  • 72
user1531038
  • 266
  • 1
  • 6
1

You are using the || operation which means if any of the condition returns true it will be true. In your case, document.documentElement.textContent will be true, so it doesn't matter if John is there or not the if condition will be true, hence the alert.

Remember: In Javascript world: Everything With a "Value" is True

DingDong
  • 86
  • 5
1

Inside the if you check index of John in a boolean Change the if condition to

document.documentElement.textContent.indexOf("John") > -1 || document.documentElement.innerText.indexOf("John") > -1 
codegames
  • 1,651
  • 18
  • 16
0

You're essentially matching the string in your javascript. That is the "John" in .indexOf("John")

Your || returns the first not null item, in this case the textContent which includes script tags. See: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#Differences_from_innerText

Just use innerText.

<script type='text/javascript'>
  window.onload = function() {

    if (document.documentElement.innerText.indexOf("John") > -1) {
      alert("Matched");
      console.log(document.documentElement.innerText);
      console.log(document.documentElement.textContent);
    }
  };
</script>


<body>
  <p> Hello! John is here </p>
</body>

See: https://stackoverflow.com/a/32158899/4665 for a good quick guide to what was going on with your || operator. It also should illustrate why && may not be the ideal fix.

Jon P
  • 19,442
  • 8
  • 49
  • 72