Check if an Element contains specific Text using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
2 min

banner

# Check if an Element contains specific Text using JavaScript

To check if an element contains specific text:

  1. Use the textContent property on the element to get the text content of the element and its descendants.
  2. Use the includes() method to check if the specific text is contained in the element.
  3. If it is, the includes() method returns true, otherwise false is returned.

Here is the HTML for the examples.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="container"> <p>Apple, Banana, Pear</p> <p>Mango, Melon, Apricot</p> </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const container = document.getElementById('container'); if (container.textContent.includes('Melon')) { console.log('✅ Melon is contained in element'); } else { console.log('⛔️ Melon is NOT contained in element'); }

check if element contains specific text

The code for this article is available on GitHub

We used the textContent property to get the text content of the element and its descendants.

We used the String.includes() method to check if the element contains the specific text.

The includes() method performs a case-sensitive search and checks if the provided string is contained in the string it was called on.

index.js
// 👇️ true console.log('apple'.includes('app')); // 👇️ false console.log('apple'.includes('banana'));

# Check if an element contains specific text ignoring the case

If you want to perform a case-insensitive check on whether the text is contained in the element, you have to convert the element's text content and the string to lowercase.

index.js
const container = document.getElementById('container'); const fruit = 'MELON'; if ( container.textContent .toLowerCase() .includes(fruit.toLowerCase()) ) { console.log('✅ melon is contained in element'); } else { console.log('⛔️ melon is NOT contained in element'); }

check if element contains specific text ignoring the case

The code for this article is available on GitHub
By converting both strings we are comparing to lowercase, we are able to perform a case-insensitive comparison.

If the text content of the element contains the specific string, our if block will run, otherwise, the else block runs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.