Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To find elements by content:
document.querySelectorAll
method to select DOM elements by tag.for...of
loop to iterate over the collection.textContent
of the element matches the
expected content.Here is the html for the example in the article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>Hello world</div> <div>One two three</div> <div>Apple banana kiwi</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const text = 'Hello world'; const matches = []; for (const div of document.querySelectorAll('div')) { if (div.textContent.includes(text)) { matches.push(div); } } console.log(matches); // 👉️ [div.box]
find()
method.We used the
document.querySelectorAll
method to get a NodeList
that contains all the DOM elements that have a tag of
div
.
The next step is to use the
for...of
loop to iterate over the NodeList
.
textContent
includes the expected text. If there is a match, we push the element into the matches
array.If you want to ignore case when checking if the DOM element's content contains the specific string, convert both strings to lowercase.
const text = 'HELLO WORLD'; const matches = []; for (const div of document.querySelectorAll('div')) { if (div.textContent.toLowerCase().includes(text.toLowerCase())) { matches.push(div); } } console.log(matches); // 👉️ [div.box]
By converting the element's textContent
and the text we are looking for to
lowercase, we are able to do a case-insensitive check.
for...of
loop iterates over all of the elements in the NodeList
, this approach would be inefficient if you only need the first element that matches the condition.To find the first DOM element whose content contains a specific string:
document.querySelectorAll
method to select elements by tag.Array.from
method.find()
method to iterate over the array.const text = 'Hello world'; const elements = Array.from(document.querySelectorAll('div')); const match = elements.find(el => { return el.textContent.includes(text); }); console.log(match); // 👉️ div.box
The function we passed to the Array.find method gets called for each element in the array until it returns a truthy value or exhausts the elements in the array.
find()
method short-circuits and returns the corresponding array element.If the condition is never met, the find
method returns undefined
.
If you want to do a case-insensitive check for whether the element contains the
specific string, convert the element's textContent
and the string you are
checking for to lowercase.
const text = 'Hello world'; const elements = Array.from(document.querySelectorAll('div')); const match = elements.find(el => { return el.textContent.toLowerCase().includes(text.toLowerCase()); }); console.log(match); // 👉️ div.box
By converting both of the strings we are comparing to lowercase, we are able to do a case-insensitive comparison.