0

Let's say I have a webpage open on my browser with source code like so:

<html>
<body>
<p>aaa</p>
<h1>yyy</h1>
<b>ccc</b>
</body>
</html>

And I had a Greasemonkey script that had a Javascript array defined like so:

var array = ['aaa', 'bbb', 'ccc', 'asds'];

Using JavaScript or JQuery, how do I search the entire text of a webpage to check if any text on the page matches any text in the array without knowing which element or class the text may reside?

  • Welcome to SO! Are you looking for `array.some(e => document.body.innerText.includes(e))`? – ggorlen Oct 18 '20 at 04:59
  • 1
    Does this answer your question? [How to check if a string contains text from an array of substrings in JavaScript?](https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript) – ggorlen Oct 18 '20 at 05:03

1 Answers1

1

I hope I have been helpful

Version 1

var array = ['aaa', 'bbb', 'ccc', 'ddd', 'asds'];
var x = document.body.innerText;

array.forEach(y => {
    if (x.indexOf(y) > -1) {
        console.log(y);
    }
});
<p>aaa</p>
<h1>yyy</h1>
<b>ccc</b>
<p><h2>ddd</h2></p>

Version 2

var array = ['aaa', 'bbb', 'ccc', 'ddd', 'asds'];
var x = document.body.children;

for (var i = 0; i < array.length; i++) {
    for (var ii = 0; ii < x.length; ii++) {
        if(array[i] === x[ii].innerText) {
            console.log(x[ii]);
        }
    }
}
<p>aaa</p>
<h1>yyy</h1>
<b>ccc</b>
<p><h2>ddd</h2></p>
54ka
  • 3,501
  • 2
  • 9
  • 24
  • OP said entire webpage; I'd assume most webpages will have more than child elements of the body. Additionally, `.innerHTML` might give false positives relative to `innerText` if a word happens to be included as a substring of a tag. Lastly, you can use `querySelector("body")` instead of `querySelectorAll("body")[0]` (or, better yet, `document.body` directly--see suggested comment above). – ggorlen Oct 18 '20 at 05:05
  • What you say is true but for the example shown by @aaausername this code works. – 54ka Oct 18 '20 at 05:10
  • 1
    Yes, it does. I'd call that _overfitting_ because if you substitute any other typical webpage except for this exact thing, it fails. A few examples it can't handle: `a = ["foo"]` HTML: `

    foo

    `, `a = ["h1"]` HTML: `

    foo

    ` or `a = ["foo"]` HTML: `

    foo bar

    `. Also, even if this were the only webpage OP was interested in extracting information from, you can still achieve the same thing in a single function call, so why not?
    – ggorlen Oct 18 '20 at 05:11
  • I agree with you! I made the changes to the code :) – 54ka Oct 18 '20 at 05:24