Check if specific Text exists on the Page using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 5, 2022

banner

Check out my new book

Check if Text exists on Page using JavaScript #

To check if specific text exists on the page, use the document.body property to access the body element and check if the text content of the body contains the text.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="background-color: salmon; width: 150px; height: 150px"> Hello world </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const text = 'Hello world'; if (document.body.textContent.includes(text)) { console.log('✅ text exists on page'); } else { console.log('⛔️ text does not exist on page'); }

We used the document.body property to get access to the body element.

The textContent property returns the text content of a node and its descendants.

When accessed on the body element, the textContent property returns the text content of all nodes on the page.

We used the String.includes method to check if the text content on the page contains the specific string.

Note that the includes method performs a case-sensitive search to determine if the substring is contained in the string the method was called on.

If you need to ignore the case when comparing the text content and the specific string, convert both of them to lowercase.

index.js
const text = 'HELLO WORLD'; if (document.body.textContent.toLowerCase().includes(text.toLowerCase())) { console.log('✅ text exists on page'); } else { console.log('⛔️ text does not exist on page'); }

By converting both of the values to lowercase, we are able to perform a case insensitive comparison.

Note that it would be faster if you narrow things down, by checking if a specific element contains the text.

For example, this code snippet checks if the div element contains the specific text.

index.js
const text = 'HELLO WORLD'; const box = document.getElementById('box'); if (box.textContent.toLowerCase().includes(text.toLowerCase())) { console.log('text exists on page'); } else { console.log('text does not exist on page'); }
Since the textContent property returns the text content of the element and all of its descendants, chances are you can select a specific element and check if it contains the text.

Accessing the textContent property on the body element means that we append the text content of every single node on the page to a string, which can be slow on pages with a lot of nested elements.

Use the search field on my Home Page to filter through my more than 3,000 articles.