:Contains Selector in jQuery
Developers can use jQuery’s :contains(“text”) selector to pick HTML elements based on whether a string is visible in their text. This capability is useful for dynamically modifying web page content by allowing actions on elements that contain certain words or phrases.
Syntax:
The :contains(“text”) selector has a simple syntax that adheres to the standard jQuery selection pattern: $(‘text_string’) in :contains selector)
:contains("text")
In this structure:
- The abbreviation for the jQuery factory function is “$”.
- “Selector” stands for any common CSS selector that first reduces the number of items to be taken into consideration, such as div, p,.myClass, and #myId. This initial section aids jQuery in locating a more extensive collection of Document Object Model (DOM) elements.
- The elements chosen by the previous selector are subjected to the custom jQuery filter “:contains selector. It makes the choice even more precise.
- The precise character sequence that the elements must have in order to be included in the final selection is known as “‘text_string'”. Single or double quote marks must enclose this text string.
How it Works
Each element in the original matched set’s combined text content is examined using the :contains(“text”) selector. An element is included in the final selection if the supplied text_string appears in its text content, including text inside any of its descendent nodes. Like what the.text() method obtains, it efficiently searches through the elements’ plain text content.
Case Sensitivity: :contains(“text”)’s case sensitivity is a crucial feature. This implies that the text_string supplied to the selection needs to precisely match the HTML element’s text capitalisation. Targeting td:contains selector (Henry), for instance, will match table cells that include “Henry” but not cells that contain “henry” (in lowercase “h”). For precise decisions, this differentiation is essential.
Filtering Capability: The function :contains selector() falls within the category of filtering selector. This indicates that it functions by honing a pre-selected set of components. For example, :contains(“Hello”) will filter all div elements that include the exact string “Hello” once you have first selected all of them. When it comes to applying particular styles, behaviours, or changes just to items that satisfy a specific content condition, this filtering capability is extremely important.
Inverse Selection with :not(): Inverted :contains() can select components without a text string when combined with :not(). Use tr:not(:contains(“topic”)) to select all table rows without “topic” content. This enables strong content-based exclusions.
Custom jQuery Selector and Performance:
- :contains selector() is a unique jQuery extension rather than a regular CSS selector that is natively supported by web browsers.
- This means jQuery executes selectors like :contains selector() using Sizzle, its internal selection engine.
- Sizzle maximises native DOM functions like querySelectorAll(), getElementById(), getElementsByTagName(), and getElementsByClassName().
- Sizzle, however, is unable to take advantage of these quicker native browser techniques for custom jQuery selectors like :contains(). It reverts to a “loop-and-test” process instead. This entails going over each gathered element one at a time and determining whether it satisfies the :contains selector() requirements.
- This “looping and testing” method is less efficient than native DOM methods for large or complicated DOM structures. It is sometimes recommended to use :contains selector() with other selectors or traversal methods that lower the initial set of elements before the filter is applied to limit the number of elements Sizzle must examine individually. This will ensure optimal performance on large web pages.
Code Example
Let’s highlight certain components on a web page to show how :contains(“text”) functions, paying particular attention to the text “Hello” and its case sensitivity.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>:contains("text") Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
div {
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
}
.green { background-color: #aaffaa; } /* Highlight for "Hello" */
.orange { background-color: #ffddaa; } /* Highlight for "hello" */
</style>
</head>
<body>
<h3>jQuery :contains("text") - Case Sensitive</h3>
<div>Hello World!</div>
<div>hello there!</div>
<div>Welcome, programmer!</div>
<script>
$(function() {
$('div:contains("Hello")').addClass('green');
$('div:contains("hello")').addClass('orange');
});
</script>
</body>
</html>
Output:
jQuery :contains("text") - Case Sensitive
Hello World!
hello there!
Welcome, programmer!
Explanation of the Code
HTML Structure: The HTML has a variety of div components, some of which contain “Hello,” while others contain “Hello” and other basic material. The behaviour of the selection can be clearly shown with this configuration.
CSS Styling: To visually differentiate the components that each search matches, two CSS classes are defined:.highlight-case-sensitive-upper (green) and.highlight-case-sensitive-lower (orange).
jQuery Code:
- By using $(document).ready(function() {… });: This common jQuery technique makes sure that the code only runs once the full HTML document has loaded and the DOM is prepared for control.
- $(‘div:contains(“Hello”)’);: var matchedCaseSensitiveUpper = $ All div elements that contain the exact string “Hello” (spelt with an uppercase “H”) are selected by this line. Since it looks for content that has descendants, it will match div1, div4, and div6.
- addedClass(‘highlight-case-sensitive-upper’);: matchedCaseSensitiveUpper These matched components are subsequently coloured green by applying the highlight-case-sensitive-upper class.
- $(‘#status-upper’).text(…): The intended behaviour is confirmed when a status message is updated to provide the number of components that the “Hello” search matched.
- var $(‘div:contains(“hello”)’);: matchedCaseSensitiveLower = $ After that, this line conducts a different search for div components that have the precise string “hello” (spelt with a lowercase “h”). Only divisions 2 and 5 will match because of case sensitivity.
- matchedCaseSensitiveLower.addClass(‘highlight-case-sensitive-lower’);: These items are coloured orange by applying the highlight-case-sensitive-lower class.
- $(‘#status-lower’).text(…): Feedback on the “hello” search results is given in another status message.
The functionality of the :contains(“text”) selector, its case sensitivity, and its capacity to search across the text content of elements including text within their descendants are all skilfully illustrated by this example.
The functionality of the :contains(“text”) selector, its case sensitivity, and its capacity to search across the text content of elements including text within their descendants are all skilfully illustrated by this example.
Conclusion
A straightforward yet powerful tool for filtering and highlighting components according to their text content is the jQuery :contains(“text”) selector. It makes it simple for developers to find items that contain a particular string and apply styles or actions appropriately. One important thing to keep in mind is that “Hello” and “hello” are treated as different values because :contains selector() is case-sensitive. Because of this, it is helpful for accurate text-based filtering, but it also needs care when handling different text situations.