How to Select Elements Containing Text in jQuery
Finding elements on a webpage based on their visible text content is
a common task in front-end development. This article explains how to
target elements using jQuery by matching specific text strings. It
covers the built-in :contains() selector for partial
matching, and demonstrates how to use the .filter() method
to achieve exact matches and case-insensitive searches.
Using the :contains()
Selector
The most direct way to select an element with specific text is using
jQuery's proprietary :contains() pseudo-class selector. It
selects all elements that contain the specified string anywhere within
their text content or child elements.
// Selects any <p> element that contains the word "Sample"
$("p:contains('Sample')");
// Selects any element on the page containing "Welcome"
$(":contains('Welcome')");Key details about :contains():
- Case-sensitive: Searching for
"sample"will not match an element containing"Sample". - Partial matching: It returns matches even if the text is embedded within a longer sentence or nested in child tags.
Selecting an Exact Text Match
Because :contains() performs a substring search, it will
match "Apples" even if you are searching for
"Apple". To select elements that match a string exactly,
use jQuery's .filter() method in combination with
JavaScript's trim() method:
$("p").filter(function() {
return $(this).text().trim() === "Apple";
});This snippet traverses all <p> elements and
returns only those whose inner text precisely matches
"Apple", ignoring surrounding whitespace.
Selecting Elements with Case-Insensitive Text
Since :contains() is strictly case-sensitive, you can
use .filter() with .toLowerCase() or a regular
expression to find elements regardless of letter casing:
Method 1: Using
.toLowerCase()
$("p").filter(function() {
return $(this).text().toLowerCase().includes("sample text");
});Method 2: Using Regular Expressions
$("p").filter(function() {
return /sample text/i.test($(this).text());
});Performance Tip
Searching through the entire DOM using
$(":contains('text')") without specifying a tag or
container can be slow on large pages. Always qualify your selector with
an element tag, class, or parent container (e.g.,
$("#content p:contains('text')")) to improve execution
speed.