Check if a Span contains specific Text using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 2, 2022

banner

Photo from Unsplash

Check if a Span contains specific Text using JavaScript #

To check if a span 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 span.
  3. If it is, the includes() method returns true, otherwise false is returned.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <span id="box"> <p>One, two, three</p> <p>Four, five, six</p> </span> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

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

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

We used the String.includes method to check if the span 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
console.log('one'.includes('ne')); // 👉️ true console.log('one'.includes('two')); // 👉️ false

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

index.js
const box = document.getElementById('box'); const word = 'FOUR'; if (box.textContent.toLowerCase().includes(word.toLowerCase())) { console.log('✅ four is contained in span'); } else { console.log('⛔️ four is NOT contained in span'); }
By converting both of the strings we are comparing to lowercase, we are able to perform a case insensitive comparison.

If the text content of the span element contains the specific text, 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.