Skip to main content

How to Find an Element by its Text Content in JavaScript

While CSS selectors are excellent for finding elements by their tag, class, or ID, there is no direct CSS selector to find an element based on its text content. This is a common requirement, for example, in testing or when you need to interact with an element that has no other unique identifier.

This guide will teach you the standard and most effective method for finding an element by its text content. You will learn how to iterate over a collection of candidate elements and check their .textContent property to find the one you need.

The Core Problem: No Direct Text Selector

You cannot write a selector like document.querySelector('button:contains("Submit")') in standard JavaScript. The DOM API requires us to perform this check manually.

The logic is a two-step process:

  1. Select Candidates: First, select a group of potential elements that might contain the text (e.g., all <div>s, all <li>s, or all elements with a specific class).
  2. Iterate and Check: Loop through these candidate elements and check the .textContent of each one to find a match.

The Solution: A Reusable findElementByText Function

The best practice is to encapsulate this logic in a reusable helper function. This function uses querySelectorAll to get the candidates and the find() array method to efficiently locate the first match.

For example, you need to find the specific <li> that contains the text "Banana".

<ul>
<li>Apple</li>
<li id="target">Banana</li>
<li>Cherry</li>
</ul>

Solution:

/**
* Finds the first element that matches a selector and contains specific text.
* @param {string} selector - A CSS selector for the candidate elements.
* @param {string} text - The text to search for.
* @returns {Element|undefined} The found element or undefined.
*/
function findElementByText(selector, text) {
const elements = document.querySelectorAll(selector);

return Array.from(elements).find(el => el.textContent.trim() === text);
}

// Example Usage:
const targetElement = findElementByText('li', 'Banana');

if (targetElement) {
targetElement.style.backgroundColor = 'yellow';
console.log('Element found:', targetElement);
} else {
console.log('No element with that text was found.');
}

How the findElementByText Function Works

  • document.querySelectorAll(selector): This selects all elements that match the provided CSS selector (e.g., all <li> elements) and returns a NodeList.
  • Array.from(elements): We convert the NodeList to a true Array so we can use standard array methods like find().
  • .find(el => ...): The find() method iterates over the array and returns the first element for which the callback function returns true.
  • el.textContent.trim() === text: This is the core check.
    • el.textContent: Gets all the text inside the element, including that of its children.
    • .trim(): A crucial step that removes any leading or trailing whitespace, which can cause an exact match to fail.
    • === text: Performs a strict, case-sensitive comparison.

How to Handle Case-Insensitive Matching

To find an element regardless of case (e.g., matching "banana", "Banana", or "BANANA"), you must convert both the element's text and your search text to the same case before comparing them.

function findElementByTextInsensitive(selector, text) {
const elements = document.querySelectorAll(selector);
const lowercasedText = text.toLowerCase();

return Array.from(elements).find(
el => el.textContent.trim().toLowerCase() === lowercasedText
);
}

// Example Usage:
const target = findElementByTextInsensitive('li', 'BANANA');
console.log(target); // Correctly finds the <li> element

How to Find All Elements with Specific Text

If you need to find all elements that contain a specific text, you can simply swap the find() method for filter().

function findAllElementsByText(selector, text) {
const elements = document.querySelectorAll(selector);

return Array.from(elements).filter(el => el.textContent.trim() === text);
}

// Example Usage:
// Assuming there are multiple <p> tags with the same text
const allMatches = findAllElementsByText('p', 'Hello World');

allMatches.forEach(el => {
el.style.color = 'blue';
});

Conclusion

While there is no direct DOM method to find an element by its text content, the process is straightforward with modern JavaScript.

  • The recommended best practice is to create a reusable function that:
    1. Selects a list of candidate elements with querySelectorAll().
    2. Converts the result to an array with Array.from().
    3. Uses the .find() method to locate the first match.
  • Always use .trim() on the .textContent to avoid issues with whitespace.
  • For case-insensitive searches, convert both strings to lowercase with .toLowerCase() before comparing.