Borislav Hadzhiev
Sun Jan 02 2022·2 min read
Photo by Yoann Boyer
To check if a div element contains specific text:
textContent
property on the element to get the text content of the
element and its descendants.includes()
method to check if the specific text is contained in the
div
.includes()
method returns true
, otherwise false
is
returned.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <p>Hello world</p> <p>One, two, three</p> </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const box = document.getElementById('box'); if (box.textContent.includes('world')) { console.log('✅ world is contained in div'); } else { console.log('⛔️ world is NOT contained in div'); }
We used the
textContent
property to get the text content of the div
element and its descendants.
We used the
String.includes
method to check if the div
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.
console.log('hello'.includes('lo')); // 👉️ true console.log('hello'.includes('test')); // 👉️ false
If you want to perform a case insensitive check whether the text is contained in
the div
element, you have to convert the element's text content and the string
you are checking for to lowercase.
const box = document.getElementById('box'); const word = 'WORLD'; if (box.textContent.toLowerCase().includes(word.toLowerCase())) { console.log('✅ world is contained in div'); } else { console.log('⛔️ world is NOT contained in div'); }
If the text content of the div
element contains the specific text, our if
block will run, otherwise the else
block runs.