jQuery Select Element by Exact Text Match
While jQuery provides the built-in :contains() selector
to find elements based on text content, it only performs a partial
match. To select an element by an exact text match, you must combine a
standard selector with jQuery's .filter() method. This
article explains the exact syntax needed to target elements containing
specific text strings without matching partial substrings or accidental
overlaps.
The Problem with
:contains()
The native jQuery :contains() pseudo-class matches any
element containing the specified string anywhere within its text.
// Matches "Apple", "Pineapple", and "Apple pie"
$("button:contains('Apple')");Because of this behavior, :contains() cannot be used for
strict equality checks.
The Exact Match Syntax
To achieve an exact match, select the candidate elements first and
use the .filter() method with a callback function that
evaluates $(this).text() against your target string:
$("selector").filter(function() {
return $(this).text() === "Exact Text";
});Handling Whitespace
HTML often introduces leading or trailing whitespace, newlines, or
indentation inside tags. To prevent whitespace from breaking the match,
apply the JavaScript .trim() method to the element's
text:
$("button").filter(function() {
return $(this).text().trim() === "Save";
});Matching Without Child Element Text
The .text() method retrieves combined text from the
selected element and all of its descendants. If the element contains
nested tags (such as <span> or
<strong>) and you only want to evaluate the parent
element's direct text node, clone the node and remove the children
before checking:
$("div").filter(function() {
return $(this).clone().children().remove().end().text().trim() === "Target Text";
});Creating a Custom Pseudo-Selector (Optional)
If your application requires frequent exact text lookups, you can extend jQuery by defining a custom pseudo-selector:
$.expr[':'].exactText = $.expr.createPseudo(function(text) {
return function(element) {
return $(element).text().trim() === text;
};
});
// Usage:
$("a:exactText('Home')");