The :contains()
pseudo-class is a powerful selector that was previously available in jQuery, and it allows you to select elements that contain a specific piece of text. This pseudo-class is very useful when you want to target elements based on their content, such as paragraphs, divs, or list items that contain certain text.
However, it is important to note that :contains()
is not a part of the official CSS specification, so it cannot be used in pure CSS. It is available only in jQuery, and we’ll explore how to use it in jQuery along with some limitations and workarounds.
1. Introduction to :contains()
The :contains()
selector in jQuery targets elements that contain the specified text. It matches any element whose text content includes the given string, regardless of whether the string appears at the start, end, or in the middle of the content.
This selector is extremely helpful when you need to find elements with specific text content on a webpage, especially when working with dynamic content or when you don’t know the exact element structure.
Syntax:
$(selector:contains('text'))
Where:
selector
: The element or elements to search within.'text'
: The string of text you want to match within the element.
2. Using :contains()
in jQuery
In jQuery, the :contains()
pseudo-class can be applied to select elements that contain specific text. It is case-sensitive by default.
Example:
$("p:contains('hello')").css("color", "blue");
In this example:
- We are selecting all
<p>
elements that contain the texthello
. - The text color of those
<p>
elements is changed to blue.
3. How :contains()
Works
The :contains()
selector checks if the inner text of an element contains the given string, but it does not check for HTML content (such as text inside child elements). It operates on the text nodes inside the element.
Example:
<ul>
<li>Item 1</li>
<li>Item 2 with text</li>
<li>Another item</li>
<li>Item 4</li>
</ul>
If you use the jQuery selector:
$("li:contains('Item 2')").css("background-color", "yellow");
It will apply the yellow background to the <li>
that contains the text Item 2 with text
, even though the text contains more than just Item 2
.
4. Case Sensitivity of :contains()
By default, :contains()
is case-sensitive. This means that searching for “hello” will not match “Hello”.
Example:
// Only matches "hello", not "Hello"
$("p:contains('hello')").css("color", "red");
To perform a case-insensitive search, you can either:
- Convert both the content and the search term to lower case, or
- Use regular expressions or custom functions.
Workaround for Case-Insensitive Search:
$("p").filter(function() {
return $(this).text().toLowerCase().indexOf("hello") !== -1;
}).css("color", "red");
Here:
- The
filter()
method checks if the text of each<p>
element contains “hello”, ignoring case.
5. Limitations of :contains()
While :contains()
is useful, it has some important limitations:
- Case Sensitivity: As mentioned, the search is case-sensitive by default.
- No Support in CSS: Unlike other pseudo-classes like
:first-child
,:nth-child
, etc.,:contains()
is not supported in CSS and is limited to jQuery. - Performance: Using
:contains()
on a large set of elements can be inefficient because jQuery needs to search through the text content of each element. - HTML Tags Inside Elements:
:contains()
only matches the raw text content, so if an element contains HTML tags, those tags are not considered during the search. You can only target the plain text inside the element.
6. Example Use Cases
Here are some practical examples of how :contains()
might be used effectively in a web development context:
Example 1: Highlighting Specific List Items
If you want to highlight list items containing specific text, :contains()
can help:
$("li:contains('apple')").css("background-color", "lightgreen");
This would apply a green background color to list items containing the word “apple”.
Example 2: Filtering Items Based on Content
If you’re building a search feature, you can dynamically filter items based on the content they contain.
$("#searchButton").click(function() {
var searchText = $("#searchInput").val();
$("ul li").filter(function() {
return $(this).text().toLowerCase().indexOf(searchText.toLowerCase()) !== -1;
}).show();
});
In this example:
- When the user clicks the search button, the script will filter the
<li>
items in the list and only show those that contain the search text, ignoring case.
Example 3: Marking Items Containing Specific Keywords
In some applications, you might want to highlight or modify items containing specific keywords.
$("p:contains('urgent')").css("font-weight", "bold");
This would make all paragraphs containing the word “urgent” bold.
7. Alternatives to :contains()
Since :contains()
is not a part of CSS, and because it has some limitations, there are some alternatives you can use for similar functionality, especially if you’re working with plain JavaScript or need more control over case sensitivity and performance.
Using JavaScript
To search for text within elements using pure JavaScript, you can use textContent
or innerText
combined with indexOf()
or regular expressions.
Example:
let elements = document.querySelectorAll("p");
elements.forEach(function(element) {
if (element.textContent.includes("hello")) {
element.style.color = "blue";
}
});
This example:
- Uses
querySelectorAll
to select all<p>
elements. - Checks if the text content of each paragraph contains the word “hello”.
- Changes the text color to blue if the condition is met.
Using Regular Expressions in JavaScript
You can also use regular expressions to find elements containing a specific text pattern in a case-insensitive way.
let elements = document.querySelectorAll("p");
elements.forEach(function(element) {
if (/hello/i.test(element.textContent)) {
element.style.color = "blue";
}
});
This regular expression (/hello/i
) matches “hello” case-insensitively.
8. Conclusion
The :contains()
pseudo-class in jQuery is a powerful tool for selecting elements based on their text content. While it’s not supported in CSS, it provides a simple way to filter elements containing specific text. However, it does have some limitations, such as case sensitivity and performance issues on large datasets.
If you’re working with jQuery, :contains()
is straightforward and easy to use. But if you’re working with vanilla JavaScript, you’ll need to use alternative approaches like textContent
or regular expressions to filter elements based on their text.
For modern web development, it’s important to keep in mind the limitations of :contains()
and consider performance when working with large datasets or dynamically changing content.